]> git.lyx.org Git - features.git/blob - src/LyXFunc.cpp
891d40b0102c47dfa729a1399f7b65739b86a462
[features.git] / src / LyXFunc.cpp
1 /**
2  * \file LyXFunc.cpp
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 #include <vector>
22
23 #include "LyXFunc.h"
24
25 #include "BranchList.h"
26 #include "buffer_funcs.h"
27 #include "Buffer.h"
28 #include "BufferList.h"
29 #include "BufferParams.h"
30 #include "BufferView.h"
31 #include "CmdDef.h"
32 #include "Color.h"
33 #include "Converter.h"
34 #include "Cursor.h"
35 #include "CutAndPaste.h"
36 #include "debug.h"
37 #include "DispatchResult.h"
38 #include "Encoding.h"
39 #include "ErrorList.h"
40 #include "Format.h"
41 #include "FuncRequest.h"
42 #include "FuncStatus.h"
43 #include "gettext.h"
44 #include "InsetIterator.h"
45 #include "Intl.h"
46 #include "KeyMap.h"
47 #include "Language.h"
48 #include "Lexer.h"
49 #include "LyXAction.h"
50 #include "lyxfind.h"
51 #include "LyX.h"
52 #include "LyXRC.h"
53 #include "LyXVC.h"
54 #include "Paragraph.h"
55 #include "ParagraphParameters.h"
56 #include "ParIterator.h"
57 #include "Row.h"
58 #include "Server.h"
59 #include "Session.h"
60 #include "TextClassList.h"
61 #include "ToolbarBackend.h"
62
63 #include "insets/InsetBox.h"
64 #include "insets/InsetBranch.h"
65 #include "insets/InsetCommand.h"
66 #include "insets/InsetERT.h"
67 #include "insets/InsetExternal.h"
68 #include "insets/InsetFloat.h"
69 #include "insets/InsetListings.h"
70 #include "insets/InsetGraphics.h"
71 #include "insets/InsetInclude.h"
72 #include "insets/InsetNote.h"
73 #include "insets/InsetTabular.h"
74 #include "insets/InsetVSpace.h"
75 #include "insets/InsetWrap.h"
76
77 #include "frontends/alert.h"
78 #include "frontends/Application.h"
79 #include "frontends/FileDialog.h"
80 #include "frontends/FontLoader.h"
81 #include "frontends/KeySymbol.h"
82 #include "frontends/LyXView.h"
83 #include "frontends/Selection.h"
84
85 #include "support/environment.h"
86 #include "support/FileFilterList.h"
87 #include "support/FileName.h"
88 #include "support/filetools.h"
89 #include "support/lstrings.h"
90 #include "support/Path.h"
91 #include "support/Package.h"
92 #include "support/Systemcall.h"
93 #include "support/convert.h"
94 #include "support/os.h"
95
96 #include <boost/current_function.hpp>
97
98 #include <sstream>
99
100 using std::endl;
101 using std::make_pair;
102 using std::pair;
103 using std::string;
104 using std::istringstream;
105 using std::ostringstream;
106 using std::find;
107 using std::vector;
108
109 namespace lyx {
110
111 using frontend::LyXView;
112
113 using support::absolutePath;
114 using support::addName;
115 using support::addPath;
116 using support::bformat;
117 using support::changeExtension;
118 using support::contains;
119 using support::FileFilterList;
120 using support::FileName;
121 using support::fileSearch;
122 using support::i18nLibFileSearch;
123 using support::makeDisplayPath;
124 using support::makeAbsPath;
125 using support::package;
126 using support::quoteName;
127 using support::rtrim;
128 using support::split;
129 using support::subst;
130 using support::Systemcall;
131 using support::token;
132 using support::trim;
133 using support::prefixIs;
134
135
136 namespace Alert = frontend::Alert;
137
138 extern bool quitting;
139 extern bool use_gui;
140
141 namespace {
142
143
144 bool import(LyXView * lv, FileName const & filename,
145                       string const & format, ErrorList & errorList)
146 {
147         docstring const displaypath = makeDisplayPath(filename.absFilename());
148         lv->message(bformat(_("Importing %1$s..."), displaypath));
149
150         FileName const lyxfile(changeExtension(filename.absFilename(), ".lyx"));
151
152         string loader_format;
153         vector<string> loaders = theConverters().loaders();
154         if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
155                 for (vector<string>::const_iterator it = loaders.begin();
156                      it != loaders.end(); ++it) {
157                         if (theConverters().isReachable(format, *it)) {
158                                 string const tofile =
159                                         changeExtension(filename.absFilename(),
160                                                 formats.extension(*it));
161                                 if (!theConverters().convert(0, filename, FileName(tofile),
162                                                         filename, format, *it, errorList))
163                                         return false;
164                                 loader_format = *it;
165                                 break;
166                         }
167                 }
168                 if (loader_format.empty()) {
169                         frontend::Alert::error(_("Couldn't import file"),
170                                      bformat(_("No information for importing the format %1$s."),
171                                          formats.prettyName(format)));
172                         return false;
173                 }
174         } else {
175                 loader_format = format;
176         }
177
178
179         if (loader_format == "lyx") {
180                 Buffer * buf = theLyXFunc().loadAndViewFile(lyxfile);
181                 if (!buf) {
182                         // we are done
183                         lv->message(_("file not imported!"));
184                         return false;
185                 }
186                 updateLabels(*buf);
187                 lv->setBuffer(buf);
188                 buf->errors("Parse");
189         } else {
190                 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
191                 if (b)
192                         lv->setBuffer(b);
193                 else
194                         return false;
195                 bool as_paragraphs = loader_format == "textparagraph";
196                 string filename2 = (loader_format == format) ? filename.absFilename()
197                         : changeExtension(filename.absFilename(),
198                                           formats.extension(loader_format));
199                 lv->view()->insertPlaintextFile(filename2, as_paragraphs);
200                 lv->dispatch(FuncRequest(LFUN_MARK_OFF), true);
201         }
202
203         // we are done
204         lv->message(_("imported."));
205         return true;
206 }
207
208
209
210 // This function runs "configure" and then rereads lyx.defaults to
211 // reconfigure the automatic settings.
212 void reconfigure(LyXView & lv, string const & option)
213 {
214         // emit message signal.
215         lv.message(_("Running configure..."));
216
217         // Run configure in user lyx directory
218         support::PathChanger p(package().user_support());
219         string configure_command = package().configure_command();
220         configure_command += option;
221         Systemcall one;
222         int ret = one.startscript(Systemcall::Wait, configure_command);
223         p.pop();
224         // emit message signal.
225         lv.message(_("Reloading configuration..."));
226         lyxrc.read(support::libFileSearch(string(), "lyxrc.defaults"));
227         // Re-read packages.lst
228         LaTeXFeatures::getAvailable();
229
230         if (ret)
231                 Alert::information(_("System reconfiguration failed"),
232                            _("The system reconfiguration has failed.\n"
233                                   "Default textclass is used but LyX may "
234                                   "not be able to work properly.\n"
235                                   "Please reconfigure again if needed."));
236         else
237
238                 Alert::information(_("System reconfigured"),
239                            _("The system has been reconfigured.\n"
240                              "You need to restart LyX to make use of any\n"
241                              "updated document class specifications."));
242 }
243
244
245 bool getLocalStatus(Cursor cursor, FuncRequest const & cmd, FuncStatus & status)
246 {
247         // Try to fix cursor in case it is broken.
248         cursor.fixIfBroken();
249
250         // This is, of course, a mess. Better create a new doc iterator and use
251         // this in Inset::getStatus. This might require an additional
252         // BufferView * arg, though (which should be avoided)
253         //Cursor safe = *this;
254         bool res = false;
255         for ( ; cursor.depth(); cursor.pop()) {
256                 //lyxerr << "\nCursor::getStatus: cmd: " << cmd << endl << *this << endl;
257                 BOOST_ASSERT(cursor.idx() <= cursor.lastidx());
258                 BOOST_ASSERT(cursor.pit() <= cursor.lastpit());
259                 BOOST_ASSERT(cursor.pos() <= cursor.lastpos());
260
261                 // The inset's getStatus() will return 'true' if it made
262                 // a definitive decision on whether it want to handle the
263                 // request or not. The result of this decision is put into
264                 // the 'status' parameter.
265                 if (cursor.inset().getStatus(cursor, cmd, status)) {
266                         res = true;
267                         break;
268                 }
269         }
270         return res;
271 }
272
273
274 /** Return the change status at cursor position, taking in account the
275  * status at each level of the document iterator (a table in a deleted
276  * footnote is deleted).
277  * When \param outer is true, the top slice is not looked at.
278  */
279 Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
280 {
281         size_t const depth = dit.depth() - (outer ? 1 : 0);
282
283         for (size_t i = 0 ; i < depth ; ++i) {
284                 CursorSlice const & slice = dit[i];
285                 if (!slice.inset().inMathed()
286                     && slice.pos() < slice.paragraph().size()) {
287                         Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
288                         if (ch != Change::UNCHANGED)
289                                 return ch;
290                 }
291         }
292         return Change::UNCHANGED;
293 }
294
295 }
296
297
298 LyXFunc::LyXFunc()
299         : lyx_view_(0), encoded_last_key(0), meta_fake_bit(NoModifier)
300 {
301 }
302
303
304 void LyXFunc::initKeySequences(KeyMap * kb)
305 {
306         keyseq = KeySequence(kb, kb);
307         cancel_meta_seq = KeySequence(kb, kb);
308 }
309
310
311 void LyXFunc::setLyXView(LyXView * lv)
312 {
313         if (!quitting && lyx_view_ && lyx_view_->view() && lyx_view_ != lv)
314                 // save current selection to the selection buffer to allow
315                 // middle-button paste in another window
316                 cap::saveSelection(lyx_view_->view()->cursor());
317         lyx_view_ = lv;
318 }
319
320
321 void LyXFunc::handleKeyFunc(kb_action action)
322 {
323         char_type c = encoded_last_key;
324
325         if (keyseq.length())
326                 c = 0;
327
328         BOOST_ASSERT(lyx_view_ && lyx_view_->view());
329         lyx_view_->view()->getIntl().getTransManager().deadkey(
330                 c, get_accent(action).accent, view()->cursor().innerText(), view()->cursor());
331         // Need to clear, in case the minibuffer calls these
332         // actions
333         keyseq.clear();
334         // copied verbatim from do_accent_char
335         view()->cursor().resetAnchor();
336         view()->processUpdateFlags(Update::FitCursor);
337 }
338
339
340 void LyXFunc::gotoBookmark(unsigned int idx, bool openFile, bool switchToBuffer)
341 {
342         BOOST_ASSERT(lyx_view_);
343         if (!LyX::ref().session().bookmarks().isValid(idx))
344                 return;
345         BookmarksSection::Bookmark const & bm = LyX::ref().session().bookmarks().bookmark(idx);
346         BOOST_ASSERT(!bm.filename.empty());
347         string const file = bm.filename.absFilename();
348         // if the file is not opened, open it.
349         if (!theBufferList().exists(file)) {
350                 if (openFile)
351                         dispatch(FuncRequest(LFUN_FILE_OPEN, file));
352                 else
353                         return;
354         }
355         // open may fail, so we need to test it again
356         if (!theBufferList().exists(file))
357                 return;
358
359         // if the current buffer is not that one, switch to it.
360         if (lyx_view_->buffer()->absFileName() != file) {
361                 if (!switchToBuffer)
362                         return;
363                 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
364         }
365         // moveToPosition try paragraph id first and then paragraph (pit, pos).
366         if (!view()->moveToPosition(bm.bottom_pit, bm.bottom_pos,
367                 bm.top_id, bm.top_pos))
368                 return;
369
370         // Cursor jump succeeded!
371         Cursor const & cur = view()->cursor();
372         pit_type new_pit = cur.pit();
373         pos_type new_pos = cur.pos();
374         int new_id = cur.paragraph().id();
375
376         // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
377         // see http://bugzilla.lyx.org/show_bug.cgi?id=3092
378         if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos 
379                 || bm.top_id != new_id) {
380                 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
381                         new_pit, new_pos, new_id);
382         }
383 }
384
385
386 void LyXFunc::processKeySym(KeySymbol const & keysym, KeyModifier state)
387 {
388         LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
389
390         // Do nothing if we have nothing (JMarc)
391         if (!keysym.isOK()) {
392                 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
393                 lyx_view_->restartCursor();
394                 return;
395         }
396
397         if (keysym.isModifier()) {
398                 LYXERR(Debug::KEY, "isModifier true");
399                 lyx_view_->restartCursor();
400                 return;
401         }
402
403         //Encoding const * encoding = view()->cursor().getEncoding();
404         //encoded_last_key = keysym.getISOEncoded(encoding ? encoding->name() : "");
405         // FIXME: encoded_last_key shadows the member variable of the same
406         // name. Is that intended?
407         char_type encoded_last_key = keysym.getUCSEncoded();
408
409         // Do a one-deep top-level lookup for
410         // cancel and meta-fake keys. RVDK_PATCH_5
411         cancel_meta_seq.reset();
412
413         FuncRequest func = cancel_meta_seq.addkey(keysym, state);
414         LYXERR(Debug::KEY, BOOST_CURRENT_FUNCTION
415                            << " action first set to [" << func.action << ']');
416
417         // When not cancel or meta-fake, do the normal lookup.
418         // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
419         // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
420         if ((func.action != LFUN_CANCEL) && (func.action != LFUN_META_PREFIX)) {
421                 // remove Caps Lock and Mod2 as a modifiers
422                 func = keyseq.addkey(keysym, (state | meta_fake_bit));
423                 LYXERR(Debug::KEY, BOOST_CURRENT_FUNCTION
424                         << "action now set to [" << func.action << ']');
425         }
426
427         // Dont remove this unless you know what you are doing.
428         meta_fake_bit = NoModifier;
429
430         // Can this happen now ?
431         if (func.action == LFUN_NOACTION)
432                 func = FuncRequest(LFUN_COMMAND_PREFIX);
433
434         LYXERR(Debug::KEY, BOOST_CURRENT_FUNCTION
435                 << " Key [action=" << func.action << "]["
436                 << to_utf8(keyseq.print(KeySequence::Portable)) << ']');
437
438         // already here we know if it any point in going further
439         // why not return already here if action == -1 and
440         // num_bytes == 0? (Lgb)
441
442         if (keyseq.length() > 1)
443                 lyx_view_->message(keyseq.print(KeySequence::ForGui));
444
445
446         // Maybe user can only reach the key via holding down shift.
447         // Let's see. But only if shift is the only modifier
448         if (func.action == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
449                 LYXERR(Debug::KEY, "Trying without shift");
450                 func = keyseq.addkey(keysym, NoModifier);
451                 LYXERR(Debug::KEY, "Action now " << func.action);
452         }
453
454         if (func.action == LFUN_UNKNOWN_ACTION) {
455                 // Hmm, we didn't match any of the keysequences. See
456                 // if it's normal insertable text not already covered
457                 // by a binding
458                 if (keysym.isText() && keyseq.length() == 1) {
459                         LYXERR(Debug::KEY, "isText() is true, inserting.");
460                         func = FuncRequest(LFUN_SELF_INSERT,
461                                            FuncRequest::KEYBOARD);
462                 } else {
463                         LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
464                         lyx_view_->message(_("Unknown function."));
465                         lyx_view_->restartCursor();
466                         return;
467                 }
468         }
469
470         if (func.action == LFUN_SELF_INSERT) {
471                 if (encoded_last_key != 0) {
472                         docstring const arg(1, encoded_last_key);
473                         dispatch(FuncRequest(LFUN_SELF_INSERT, arg,
474                                              FuncRequest::KEYBOARD));
475                         LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
476                 }
477         } else {
478                 dispatch(func);
479         }
480
481         lyx_view_->restartCursor();
482 }
483
484
485 FuncStatus LyXFunc::getStatus(FuncRequest const & cmd) const
486 {
487         //lyxerr << "LyXFunc::getStatus: cmd: " << cmd << endl;
488         FuncStatus flag;
489
490         Buffer * buf = lyx_view_? lyx_view_->buffer() : 0;
491
492         if (cmd.action == LFUN_NOACTION) {
493                 flag.message(from_utf8(N_("Nothing to do")));
494                 flag.enabled(false);
495                 return flag;
496         }
497
498         switch (cmd.action) {
499         case LFUN_UNKNOWN_ACTION:
500 #ifndef HAVE_LIBAIKSAURUS
501         case LFUN_THESAURUS_ENTRY:
502 #endif
503                 flag.unknown(true);
504                 flag.enabled(false);
505                 break;
506
507         default:
508                 break;
509         }
510
511         if (flag.unknown()) {
512                 flag.message(from_utf8(N_("Unknown action")));
513                 return flag;
514         }
515
516         if (!flag.enabled()) {
517                 if (flag.message().empty())
518                         flag.message(from_utf8(N_("Command disabled")));
519                 return flag;
520         }
521
522         // Check whether we need a buffer
523         if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
524                 // no, exit directly
525                 flag.message(from_utf8(N_("Command not allowed with"
526                                     "out any document open")));
527                 flag.enabled(false);
528                 return flag;
529         }
530
531         // I would really like to avoid having this switch and rather try to
532         // encode this in the function itself.
533         // -- And I'd rather let an inset decide which LFUNs it is willing
534         // to handle (Andre')
535         bool enable = true;
536         switch (cmd.action) {
537
538         case LFUN_WINDOW_CLOSE:
539                 if (theApp())
540                         return theApp()->getStatus(cmd);
541                 enable = false;
542                 break;
543
544         case LFUN_DIALOG_TOGGLE:
545         case LFUN_DIALOG_SHOW:
546         case LFUN_DIALOG_UPDATE:
547         case LFUN_TOOLBAR_TOGGLE:
548         case LFUN_INSET_APPLY:
549                 if (lyx_view_)
550                         return lyx_view_->getStatus(cmd);
551                 enable = false;
552                 break;
553
554         case LFUN_BUFFER_TOGGLE_READ_ONLY:
555                 flag.setOnOff(buf->isReadonly());
556                 break;
557
558         case LFUN_BUFFER_SWITCH:
559                 // toggle on the current buffer, but do not toggle off
560                 // the other ones (is that a good idea?)
561                 if (buf && to_utf8(cmd.argument()) == buf->absFileName())
562                         flag.setOnOff(true);
563                 break;
564
565         case LFUN_BUFFER_EXPORT:
566                 enable = cmd.argument() == "custom"
567                         || buf->isExportable(to_utf8(cmd.argument()));
568                 break;
569
570         case LFUN_BUFFER_CHKTEX:
571                 enable = buf->isLatex() && !lyxrc.chktex_command.empty();
572                 break;
573
574         case LFUN_BUILD_PROGRAM:
575                 enable = buf->isExportable("program");
576                 break;
577
578         case LFUN_VC_REGISTER:
579                 enable = !buf->lyxvc().inUse();
580                 break;
581         case LFUN_VC_CHECK_IN:
582                 enable = buf->lyxvc().inUse() && !buf->isReadonly();
583                 break;
584         case LFUN_VC_CHECK_OUT:
585                 enable = buf->lyxvc().inUse() && buf->isReadonly();
586                 break;
587         case LFUN_VC_REVERT:
588         case LFUN_VC_UNDO_LAST:
589                 enable = buf->lyxvc().inUse();
590                 break;
591         case LFUN_BUFFER_RELOAD:
592                 enable = !buf->isUnnamed() && buf->fileName().exists()
593                         && (!buf->isClean() || buf->isExternallyModified(Buffer::timestamp_method));
594                 break;
595
596         case LFUN_CITATION_INSERT: {
597                 FuncRequest fr(LFUN_INSET_INSERT, "citation");
598                 enable = getStatus(fr).enabled();
599                 break;
600         }
601
602         case LFUN_BUFFER_WRITE: {
603                 enable = lyx_view_->buffer()->isUnnamed()
604                         || !lyx_view_->buffer()->isClean();
605                 break;
606         }
607
608
609         case LFUN_BUFFER_WRITE_ALL: {
610         // We enable the command only if there are some modified buffers
611                 Buffer * first = theBufferList().first();
612                 bool modified = false;
613                 if (first) {
614                         Buffer * b = first;
615                 
616                 // We cannot use a for loop as the buffer list is a cycle.
617                         do {
618                                 if (!b->isClean()) {
619                                         modified = true;
620                                         break;
621                                 }
622                                 b = theBufferList().next(b);
623                         } while (b != first); 
624                 }
625         
626                 enable = modified;
627
628                 break;
629         }
630
631         case LFUN_BOOKMARK_GOTO: {
632                 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
633                 enable = LyX::ref().session().bookmarks().isValid(num);
634                 break;
635         }
636
637         case LFUN_BOOKMARK_CLEAR:
638                 enable = LyX::ref().session().bookmarks().size() > 0;
639                 break;
640
641         // this one is difficult to get right. As a half-baked
642         // solution, we consider only the first action of the sequence
643         case LFUN_COMMAND_SEQUENCE: {
644                 // argument contains ';'-terminated commands
645                 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
646                 FuncRequest func(lyxaction.lookupFunc(firstcmd));
647                 func.origin = cmd.origin;
648                 flag = getStatus(func);
649                 break;
650         }
651
652         case LFUN_CALL: {
653                 FuncRequest func;
654                 std::string name = to_utf8(cmd.argument());
655                 if (LyX::ref().topLevelCmdDef().lock(name, func)) {
656                         func.origin = cmd.origin;
657                         flag = getStatus(func);
658                         LyX::ref().topLevelCmdDef().release(name);
659                 } else {
660                         // catch recursion or unknown command definiton
661                         // all operations until the recursion or unknown command 
662                         // definiton occures are performed, so set the state to enabled
663                         enable = true;
664                 }
665                 break;
666         }
667
668         case LFUN_BUFFER_NEW:
669         case LFUN_BUFFER_NEW_TEMPLATE:
670         case LFUN_WORD_FIND_FORWARD:
671         case LFUN_WORD_FIND_BACKWARD:
672         case LFUN_COMMAND_PREFIX:
673         case LFUN_COMMAND_EXECUTE:
674         case LFUN_CANCEL:
675         case LFUN_META_PREFIX:
676         case LFUN_BUFFER_CLOSE:
677         case LFUN_BUFFER_WRITE_AS:
678         case LFUN_BUFFER_UPDATE:
679         case LFUN_BUFFER_VIEW:
680         case LFUN_MASTER_BUFFER_UPDATE:
681         case LFUN_MASTER_BUFFER_VIEW:
682         case LFUN_BUFFER_IMPORT:
683         case LFUN_BUFFER_AUTO_SAVE:
684         case LFUN_RECONFIGURE:
685         case LFUN_HELP_OPEN:
686         case LFUN_FILE_NEW:
687         case LFUN_FILE_OPEN:
688         case LFUN_DROP_LAYOUTS_CHOICE:
689         case LFUN_MENU_OPEN:
690         case LFUN_SERVER_GET_NAME:
691         case LFUN_SERVER_NOTIFY:
692         case LFUN_SERVER_GOTO_FILE_ROW:
693         case LFUN_DIALOG_HIDE:
694         case LFUN_DIALOG_DISCONNECT_INSET:
695         case LFUN_BUFFER_CHILD_OPEN:
696         case LFUN_TOGGLE_CURSOR_FOLLOWS_SCROLLBAR:
697         case LFUN_KEYMAP_OFF:
698         case LFUN_KEYMAP_PRIMARY:
699         case LFUN_KEYMAP_SECONDARY:
700         case LFUN_KEYMAP_TOGGLE:
701         case LFUN_REPEAT:
702         case LFUN_BUFFER_EXPORT_CUSTOM:
703         case LFUN_BUFFER_PRINT:
704         case LFUN_PREFERENCES_SAVE:
705         case LFUN_SCREEN_FONT_UPDATE:
706         case LFUN_SET_COLOR:
707         case LFUN_MESSAGE:
708         case LFUN_EXTERNAL_EDIT:
709         case LFUN_GRAPHICS_EDIT:
710         case LFUN_ALL_INSETS_TOGGLE:
711         case LFUN_BUFFER_LANGUAGE:
712         case LFUN_TEXTCLASS_APPLY:
713         case LFUN_TEXTCLASS_LOAD:
714         case LFUN_BUFFER_SAVE_AS_DEFAULT:
715         case LFUN_BUFFER_PARAMS_APPLY:
716         case LFUN_LAYOUT_MODULES_CLEAR:
717         case LFUN_LAYOUT_MODULE_ADD:
718         case LFUN_LAYOUT_RELOAD:
719         case LFUN_LYXRC_APPLY:
720         case LFUN_BUFFER_NEXT:
721         case LFUN_BUFFER_PREVIOUS:
722         case LFUN_WINDOW_NEW:
723         case LFUN_LYX_QUIT:
724                 // these are handled in our dispatch()
725                 break;
726
727         default:
728                 if (!view()) {
729                         enable = false;
730                         break;
731                 }
732                 if (!getLocalStatus(view()->cursor(), cmd, flag))
733                         flag = view()->getStatus(cmd);
734         }
735
736         if (!enable)
737                 flag.enabled(false);
738
739         // Can we use a readonly buffer?
740         if (buf && buf->isReadonly()
741             && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
742             && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
743                 flag.message(from_utf8(N_("Document is read-only")));
744                 flag.enabled(false);
745         }
746
747         // Are we in a DELETED change-tracking region?
748         if (buf && view() 
749                 && lookupChangeType(view()->cursor(), true) == Change::DELETED
750             && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
751             && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
752                 flag.message(from_utf8(N_("This portion of the document is deleted.")));
753                 flag.enabled(false);
754         }
755
756         // the default error message if we disable the command
757         if (!flag.enabled() && flag.message().empty())
758                 flag.message(from_utf8(N_("Command disabled")));
759
760         return flag;
761 }
762
763
764 bool LyXFunc::ensureBufferClean(BufferView * bv)
765 {
766         Buffer & buf = bv->buffer();
767         if (buf.isClean())
768                 return true;
769
770         docstring const file = buf.fileName().displayName(30);
771         docstring text = bformat(_("The document %1$s has unsaved "
772                                              "changes.\n\nDo you want to save "
773                                              "the document?"), file);
774         int const ret = Alert::prompt(_("Save changed document?"),
775                                       text, 0, 1, _("&Save"),
776                                       _("&Cancel"));
777
778         if (ret == 0)
779                 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
780
781         return buf.isClean();
782 }
783
784
785 namespace {
786
787 void showPrintError(string const & name)
788 {
789         docstring str = bformat(_("Could not print the document %1$s.\n"
790                                             "Check that your printer is set up correctly."),
791                              makeDisplayPath(name, 50));
792         Alert::error(_("Print document failed"), str);
793 }
794
795
796 void loadTextClass(string const & name)
797 {
798         std::pair<bool, textclass_type> const tc_pair =
799                 textclasslist.numberOfClass(name);
800
801         if (!tc_pair.first) {
802                 lyxerr << "Document class \"" << name
803                        << "\" does not exist."
804                        << std::endl;
805                 return;
806         }
807
808         textclass_type const tc = tc_pair.second;
809
810         if (!textclasslist[tc].load()) {
811                 docstring s = bformat(_("The document class %1$s."
812                                    "could not be loaded."),
813                                    from_utf8(textclasslist[tc].name()));
814                 Alert::error(_("Could not load class"), s);
815         }
816 }
817
818
819 void actOnUpdatedPrefs(LyXRC const & lyxrc_orig, LyXRC const & lyxrc_new);
820
821 } //namespace anon
822
823
824 void LyXFunc::dispatch(FuncRequest const & cmd)
825 {
826         string const argument = to_utf8(cmd.argument());
827         kb_action const action = cmd.action;
828
829         LYXERR(Debug::ACTION, "\nLyXFunc::dispatch: cmd: " << cmd);
830         //lyxerr << "LyXFunc::dispatch: cmd: " << cmd << endl;
831
832         // we have not done anything wrong yet.
833         errorstat = false;
834         dispatch_buffer.erase();
835
836         // redraw the screen at the end (first of the two drawing steps).
837         //This is done unless explicitely requested otherwise
838         Update::flags updateFlags = Update::FitCursor;
839
840         FuncStatus const flag = getStatus(cmd);
841         if (!flag.enabled()) {
842                 // We cannot use this function here
843                 LYXERR(Debug::ACTION, "LyXFunc::dispatch: "
844                        << lyxaction.getActionName(action)
845                        << " [" << action << "] is disabled at this location");
846                 setErrorMessage(flag.message());
847         } else {
848                 switch (action) {
849
850                 case LFUN_WORD_FIND_FORWARD:
851                 case LFUN_WORD_FIND_BACKWARD: {
852                         BOOST_ASSERT(lyx_view_ && lyx_view_->view());
853                         static docstring last_search;
854                         docstring searched_string;
855
856                         if (!cmd.argument().empty()) {
857                                 last_search = cmd.argument();
858                                 searched_string = cmd.argument();
859                         } else {
860                                 searched_string = last_search;
861                         }
862
863                         if (searched_string.empty())
864                                 break;
865
866                         bool const fw = action == LFUN_WORD_FIND_FORWARD;
867                         docstring const data =
868                                 find2string(searched_string, true, false, fw);
869                         find(view(), FuncRequest(LFUN_WORD_FIND, data));
870                         break;
871                 }
872
873                 case LFUN_COMMAND_PREFIX:
874                         BOOST_ASSERT(lyx_view_);
875                         lyx_view_->message(keyseq.printOptions(true));
876                         break;
877
878                 case LFUN_CANCEL:
879                         BOOST_ASSERT(lyx_view_ && lyx_view_->view());
880                         keyseq.reset();
881                         meta_fake_bit = NoModifier;
882                         if (lyx_view_->buffer())
883                                 // cancel any selection
884                                 dispatch(FuncRequest(LFUN_MARK_OFF));
885                         setMessage(from_ascii(N_("Cancel")));
886                         break;
887
888                 case LFUN_META_PREFIX:
889                         meta_fake_bit = AltModifier;
890                         setMessage(keyseq.print(KeySequence::ForGui));
891                         break;
892
893                 case LFUN_BUFFER_TOGGLE_READ_ONLY: {
894                         BOOST_ASSERT(lyx_view_ && lyx_view_->view() && lyx_view_->buffer());
895                         Buffer * buf = lyx_view_->buffer();
896                         if (buf->lyxvc().inUse())
897                                 buf->lyxvc().toggleReadOnly();
898                         else
899                                 buf->setReadonly(!lyx_view_->buffer()->isReadonly());
900                         break;
901                 }
902
903                 // --- Menus -----------------------------------------------
904                 case LFUN_BUFFER_NEW:
905                         menuNew(argument, false);
906                         updateFlags = Update::None;
907                         break;
908
909                 case LFUN_BUFFER_NEW_TEMPLATE:
910                         menuNew(argument, true);
911                         updateFlags = Update::None;
912                         break;
913
914                 case LFUN_BUFFER_CLOSE:
915                         closeBuffer();
916                         updateFlags = Update::None;
917                         break;
918
919                 case LFUN_BUFFER_WRITE:
920                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
921                         if (!lyx_view_->buffer()->isUnnamed()) {
922                                 docstring const str = bformat(_("Saving document %1$s..."),
923                                          makeDisplayPath(lyx_view_->buffer()->absFileName()));
924                                 lyx_view_->message(str);
925                                 lyx_view_->buffer()->menuWrite();
926                                 lyx_view_->message(str + _(" done."));
927                         } else {
928                                 lyx_view_->buffer()->writeAs();
929                         }
930                         updateFlags = Update::None;
931                         break;
932
933                 case LFUN_BUFFER_WRITE_AS:
934                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
935                         lyx_view_->buffer()->writeAs(argument);
936                         updateFlags = Update::None;
937                         break;
938
939                 case LFUN_BUFFER_WRITE_ALL: {
940                         Buffer * first = theBufferList().first();
941                         if (first) {
942                                 Buffer * b = first;
943                                 lyx_view_->message(_("Saving all documents..."));
944                 
945                                 // We cannot use a for loop as the buffer list cycles.
946                                 do {
947                                         if (!b->isClean()) {
948                                                 if (!b->isUnnamed()) {
949                                                         b->menuWrite();
950                                                         lyxerr[Debug::ACTION] << "Saved " << b->absFileName() << endl;
951                                                 } else
952                                                         b->writeAs();
953                                         }
954                                         b = theBufferList().next(b);
955                                 } while (b != first); 
956                                 lyx_view_->message(_("All documents saved."));
957                         } 
958         
959                         updateFlags = Update::None;
960                         break;
961                 }
962
963                 case LFUN_BUFFER_RELOAD: {
964                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
965                         docstring const file = makeDisplayPath(lyx_view_->buffer()->absFileName(), 20);
966                         docstring text = bformat(_("Any changes will be lost. Are you sure "
967                                                              "you want to revert to the saved version of the document %1$s?"), file);
968                         int const ret = Alert::prompt(_("Revert to saved document?"),
969                                 text, 1, 1, _("&Revert"), _("&Cancel"));
970
971                         if (ret == 0)
972                                 reloadBuffer();
973                         break;
974                 }
975
976                 case LFUN_BUFFER_UPDATE:
977                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
978                         lyx_view_->buffer()->doExport(argument, true);
979                         break;
980
981                 case LFUN_BUFFER_VIEW:
982                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
983                         lyx_view_->buffer()->preview(argument);
984                         break;
985
986                 case LFUN_MASTER_BUFFER_UPDATE:
987                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer() && lyx_view_->buffer()->masterBuffer());
988                         lyx_view_->buffer()->masterBuffer()->doExport(argument, true);
989                         break;
990
991                 case LFUN_MASTER_BUFFER_VIEW:
992                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer() && lyx_view_->buffer()->masterBuffer());
993                         lyx_view_->buffer()->masterBuffer()->preview(argument);
994                         break;
995
996                 case LFUN_BUILD_PROGRAM:
997                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
998                         lyx_view_->buffer()->doExport("program", true);
999                         break;
1000
1001                 case LFUN_BUFFER_CHKTEX:
1002                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1003                         lyx_view_->buffer()->runChktex();
1004                         break;
1005
1006                 case LFUN_BUFFER_EXPORT:
1007                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1008                         if (argument == "custom")
1009                                 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"));
1010                         else
1011                                 lyx_view_->buffer()->doExport(argument, false);
1012                         break;
1013
1014                 case LFUN_BUFFER_EXPORT_CUSTOM: {
1015                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1016                         string format_name;
1017                         string command = split(argument, format_name, ' ');
1018                         Format const * format = formats.getFormat(format_name);
1019                         if (!format) {
1020                                 lyxerr << "Format \"" << format_name
1021                                        << "\" not recognized!"
1022                                        << std::endl;
1023                                 break;
1024                         }
1025
1026                         Buffer * buffer = lyx_view_->buffer();
1027
1028                         // The name of the file created by the conversion process
1029                         string filename;
1030
1031                         // Output to filename
1032                         if (format->name() == "lyx") {
1033                                 string const latexname = buffer->latexName(false);
1034                                 filename = changeExtension(latexname,
1035                                                            format->extension());
1036                                 filename = addName(buffer->temppath(), filename);
1037
1038                                 if (!buffer->writeFile(FileName(filename)))
1039                                         break;
1040
1041                         } else {
1042                                 buffer->doExport(format_name, true, filename);
1043                         }
1044
1045                         // Substitute $$FName for filename
1046                         if (!contains(command, "$$FName"))
1047                                 command = "( " + command + " ) < $$FName";
1048                         command = subst(command, "$$FName", filename);
1049
1050                         // Execute the command in the background
1051                         Systemcall call;
1052                         call.startscript(Systemcall::DontWait, command);
1053                         break;
1054                 }
1055
1056                 case LFUN_BUFFER_PRINT: {
1057                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1058                         // FIXME: cmd.getArg() might fail if one of the arguments
1059                         // contains double quotes
1060                         string target = cmd.getArg(0);
1061                         string target_name = cmd.getArg(1);
1062                         string command = cmd.getArg(2);
1063
1064                         if (target.empty()
1065                             || target_name.empty()
1066                             || command.empty()) {
1067                                 lyxerr << "Unable to parse \""
1068                                        << argument << '"' << endl;
1069                                 break;
1070                         }
1071                         if (target != "printer" && target != "file") {
1072                                 lyxerr << "Unrecognized target \""
1073                                        << target << '"' << endl;
1074                                 break;
1075                         }
1076
1077                         Buffer * buffer = lyx_view_->buffer();
1078
1079                         if (!buffer->doExport("dvi", true)) {
1080                                 showPrintError(buffer->absFileName());
1081                                 break;
1082                         }
1083
1084                         // Push directory path.
1085                         string const path = buffer->temppath();
1086                         // Prevent the compiler from optimizing away p
1087                         FileName pp(path);
1088                         support::PathChanger p(pp);
1089
1090                         // there are three cases here:
1091                         // 1. we print to a file
1092                         // 2. we print directly to a printer
1093                         // 3. we print using a spool command (print to file first)
1094                         Systemcall one;
1095                         int res = 0;
1096                         string const dviname =
1097                                 changeExtension(buffer->latexName(true), "dvi");
1098
1099                         if (target == "printer") {
1100                                 if (!lyxrc.print_spool_command.empty()) {
1101                                         // case 3: print using a spool
1102                                         string const psname =
1103                                                 changeExtension(dviname,".ps");
1104                                         command += ' ' + lyxrc.print_to_file
1105                                                 + quoteName(psname)
1106                                                 + ' '
1107                                                 + quoteName(dviname);
1108
1109                                         string command2 =
1110                                                 lyxrc.print_spool_command + ' ';
1111                                         if (target_name != "default") {
1112                                                 command2 += lyxrc.print_spool_printerprefix
1113                                                         + target_name
1114                                                         + ' ';
1115                                         }
1116                                         command2 += quoteName(psname);
1117                                         // First run dvips.
1118                                         // If successful, then spool command
1119                                         res = one.startscript(
1120                                                 Systemcall::Wait,
1121                                                 command);
1122
1123                                         if (res == 0)
1124                                                 res = one.startscript(
1125                                                         Systemcall::DontWait,
1126                                                         command2);
1127                                 } else {
1128                                         // case 2: print directly to a printer
1129                                         if (target_name != "default")
1130                                                 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
1131                                         res = one.startscript(
1132                                                 Systemcall::DontWait,
1133                                                 command + quoteName(dviname));
1134                                 }
1135
1136                         } else {
1137                                 // case 1: print to a file
1138                                 FileName const filename(makeAbsPath(target_name,
1139                                                         lyx_view_->buffer()->filePath()));
1140                                 FileName const dvifile(makeAbsPath(dviname, path));
1141                                 if (filename.exists()) {
1142                                         docstring text = bformat(
1143                                                 _("The file %1$s already exists.\n\n"
1144                                                   "Do you want to overwrite that file?"),
1145                                                 makeDisplayPath(filename.absFilename()));
1146                                         if (Alert::prompt(_("Overwrite file?"),
1147                                             text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
1148                                                 break;
1149                                 }
1150                                 command += ' ' + lyxrc.print_to_file
1151                                         + quoteName(filename.toFilesystemEncoding())
1152                                         + ' '
1153                                         + quoteName(dvifile.toFilesystemEncoding());
1154                                 res = one.startscript(Systemcall::DontWait,
1155                                                       command);
1156                         }
1157
1158                         if (res != 0)
1159                                 showPrintError(buffer->absFileName());
1160                         break;
1161                 }
1162
1163                 case LFUN_BUFFER_IMPORT:
1164                         doImport(argument);
1165                         break;
1166
1167                 case LFUN_BUFFER_AUTO_SAVE:
1168                         lyx_view_->buffer()->autoSave();
1169                         break;
1170
1171                 case LFUN_RECONFIGURE:
1172                         BOOST_ASSERT(lyx_view_);
1173                         // argument is any additional parameter to the configure.py command
1174                         reconfigure(*lyx_view_, argument);
1175                         break;
1176
1177                 case LFUN_HELP_OPEN: {
1178                         BOOST_ASSERT(lyx_view_);
1179                         string const arg = argument;
1180                         if (arg.empty()) {
1181                                 setErrorMessage(from_ascii(N_("Missing argument")));
1182                                 break;
1183                         }
1184                         FileName const fname = i18nLibFileSearch("doc", arg, "lyx");
1185                         if (fname.empty()) {
1186                                 lyxerr << "LyX: unable to find documentation file `"
1187                                                          << arg << "'. Bad installation?" << endl;
1188                                 break;
1189                         }
1190                         lyx_view_->message(bformat(_("Opening help file %1$s..."),
1191                                 makeDisplayPath(fname.absFilename())));
1192                         Buffer * buf = loadAndViewFile(fname, false);
1193                         if (buf) {
1194                                 updateLabels(*buf);
1195                                 lyx_view_->setBuffer(buf);
1196                                 buf->errors("Parse");
1197                         }
1198                         updateFlags = Update::None;
1199                         break;
1200                 }
1201
1202                 // --- version control -------------------------------
1203                 case LFUN_VC_REGISTER:
1204                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1205                         if (!ensureBufferClean(view()))
1206                                 break;
1207                         if (!lyx_view_->buffer()->lyxvc().inUse()) {
1208                                 lyx_view_->buffer()->lyxvc().registrer();
1209                                 reloadBuffer();
1210                         }
1211                         updateFlags = Update::Force;
1212                         break;
1213
1214                 case LFUN_VC_CHECK_IN:
1215                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1216                         if (!ensureBufferClean(view()))
1217                                 break;
1218                         if (lyx_view_->buffer()->lyxvc().inUse()
1219                                         && !lyx_view_->buffer()->isReadonly()) {
1220                                 lyx_view_->buffer()->lyxvc().checkIn();
1221                                 reloadBuffer();
1222                         }
1223                         break;
1224
1225                 case LFUN_VC_CHECK_OUT:
1226                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1227                         if (!ensureBufferClean(view()))
1228                                 break;
1229                         if (lyx_view_->buffer()->lyxvc().inUse()
1230                                         && lyx_view_->buffer()->isReadonly()) {
1231                                 lyx_view_->buffer()->lyxvc().checkOut();
1232                                 reloadBuffer();
1233                         }
1234                         break;
1235
1236                 case LFUN_VC_REVERT:
1237                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1238                         lyx_view_->buffer()->lyxvc().revert();
1239                         reloadBuffer();
1240                         break;
1241
1242                 case LFUN_VC_UNDO_LAST:
1243                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1244                         lyx_view_->buffer()->lyxvc().undoLast();
1245                         reloadBuffer();
1246                         break;
1247
1248                 // --- buffers ----------------------------------------
1249
1250                 case LFUN_FILE_NEW: {
1251                         BOOST_ASSERT(lyx_view_);
1252                         string name;
1253                         string tmpname = split(argument, name, ':'); // Split filename
1254                         Buffer * const b = newFile(name, tmpname);
1255                         if (b)
1256                                 lyx_view_->setBuffer(b);
1257                         updateFlags = Update::None;
1258                         break;
1259                 }
1260
1261                 case LFUN_FILE_OPEN:
1262                         BOOST_ASSERT(lyx_view_);
1263                         open(argument);
1264                         updateFlags = Update::None;
1265                         break;
1266
1267                 // --- lyxserver commands ----------------------------
1268                 case LFUN_SERVER_GET_NAME:
1269                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1270                         setMessage(from_utf8(lyx_view_->buffer()->absFileName()));
1271                         LYXERR(Debug::INFO, "FNAME["
1272                                 << lyx_view_->buffer()->absFileName() << ']');
1273                         break;
1274
1275                 case LFUN_SERVER_NOTIFY:
1276                         dispatch_buffer = keyseq.print(KeySequence::Portable);
1277                         theServer().notifyClient(to_utf8(dispatch_buffer));
1278                         break;
1279
1280                 case LFUN_SERVER_GOTO_FILE_ROW: {
1281                         BOOST_ASSERT(lyx_view_);
1282                         string file_name;
1283                         int row;
1284                         istringstream is(argument);
1285                         is >> file_name >> row;
1286                         Buffer * buf = 0;
1287                         bool loaded = false;
1288                         if (prefixIs(file_name, package().temp_dir().absFilename()))
1289                                 // Needed by inverse dvi search. If it is a file
1290                                 // in tmpdir, call the apropriated function
1291                                 buf = theBufferList().getBufferFromTmp(file_name);
1292                         else {
1293                                 // Must replace extension of the file to be .lyx
1294                                 // and get full path
1295                                 FileName const s = fileSearch(string(), changeExtension(file_name, ".lyx"), "lyx");
1296                                 // Either change buffer or load the file
1297                                 if (theBufferList().exists(s.absFilename()))
1298                                         buf = theBufferList().getBuffer(s.absFilename());
1299                                 else {
1300                                         buf = loadAndViewFile(s);
1301                                         loaded = true;
1302                                 }
1303                         }
1304
1305                         if (!buf) {
1306                                 updateFlags = Update::None;
1307                                 break;
1308                         }
1309
1310                         updateLabels(*buf);
1311                         lyx_view_->setBuffer(buf);
1312                         view()->setCursorFromRow(row);
1313                         if (loaded)
1314                                 buf->errors("Parse");
1315                         updateFlags = Update::FitCursor;
1316                         break;
1317                 }
1318
1319
1320                 case LFUN_DIALOG_SHOW_NEW_INSET: {
1321                         BOOST_ASSERT(lyx_view_);
1322                         string const name = cmd.getArg(0);
1323                         InsetCode code = insetCode(name);
1324                         string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1325                         bool insetCodeOK = true;
1326                         switch (code) {
1327                         case BIBITEM_CODE:
1328                         case BIBTEX_CODE:
1329                         case INDEX_CODE:
1330                         case LABEL_CODE:
1331                         case NOMENCL_CODE:
1332                         case REF_CODE:
1333                         case TOC_CODE:
1334                         case HYPERLINK_CODE: {
1335                                 InsetCommandParams p(code);
1336                                 data = InsetCommandMailer::params2string(name, p);
1337                                 break;
1338                         } 
1339                         case INCLUDE_CODE: {
1340                                 // data is the include type: one of "include",
1341                                 // "input", "verbatiminput" or "verbatiminput*"
1342                                 if (data.empty())
1343                                         // default type is requested
1344                                         data = "include";
1345                                 InsetCommandParams p(INCLUDE_CODE, data);
1346                                 data = InsetCommandMailer::params2string("include", p);
1347                                 break;
1348                         } 
1349                         case BOX_CODE: {
1350                                 // \c data == "Boxed" || "Frameless" etc
1351                                 InsetBoxParams p(data);
1352                                 data = InsetBoxMailer::params2string(p);
1353                                 break;
1354                         } 
1355                         case BRANCH_CODE: {
1356                                 InsetBranchParams p;
1357                                 data = InsetBranchMailer::params2string(p);
1358                                 break;
1359                         } 
1360                         case CITE_CODE: {
1361                                 InsetCommandParams p(CITE_CODE);
1362                                 data = InsetCommandMailer::params2string(name, p);
1363                                 break;
1364                         } 
1365                         case ERT_CODE: {
1366                                 data = InsetERTMailer::params2string(InsetCollapsable::Open);
1367                                 break;
1368                         } 
1369                         case EXTERNAL_CODE: {
1370                                 InsetExternalParams p;
1371                                 Buffer const & buffer = *lyx_view_->buffer();
1372                                 data = InsetExternalMailer::params2string(p, buffer);
1373                                 break;
1374                         } 
1375                         case FLOAT_CODE:  {
1376                                 InsetFloatParams p;
1377                                 data = InsetFloatMailer::params2string(p);
1378                                 break;
1379                         } 
1380                         case LISTINGS_CODE: {
1381                                 InsetListingsParams p;
1382                                 data = InsetListingsMailer::params2string(p);
1383                                 break;
1384                         } 
1385                         case GRAPHICS_CODE: {
1386                                 InsetGraphicsParams p;
1387                                 Buffer const & buffer = *lyx_view_->buffer();
1388                                 data = InsetGraphicsMailer::params2string(p, buffer);
1389                                 break;
1390                         } 
1391                         case NOTE_CODE: {
1392                                 InsetNoteParams p;
1393                                 data = InsetNoteMailer::params2string(p);
1394                                 break;
1395                         } 
1396                         case VSPACE_CODE: {
1397                                 VSpace space;
1398                                 data = InsetVSpaceMailer::params2string(space);
1399                                 break;
1400                         } 
1401                         case WRAP_CODE: {
1402                                 InsetWrapParams p;
1403                                 data = InsetWrapMailer::params2string(p);
1404                                 break;
1405                         }
1406                         default:
1407                                 lyxerr << "Inset type '" << name << 
1408                                         "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << std:: endl;
1409                                 insetCodeOK = false;
1410                                 break;
1411                         } // end switch(code)
1412                         if (insetCodeOK)
1413                                 dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1414                         break;
1415                 }
1416
1417                 case LFUN_CITATION_INSERT: {
1418                         BOOST_ASSERT(lyx_view_);
1419                         if (!argument.empty()) {
1420                                 // we can have one optional argument, delimited by '|'
1421                                 // citation-insert <key>|<text_before>
1422                                 // this should be enhanced to also support text_after
1423                                 // and citation style
1424                                 string arg = argument;
1425                                 string opt1;
1426                                 if (contains(argument, "|")) {
1427                                         arg = token(argument, '|', 0);
1428                                         opt1 = token(argument, '|', 1);
1429                                 }
1430                                 InsetCommandParams icp(CITE_CODE);
1431                                 icp["key"] = from_utf8(arg);
1432                                 if (!opt1.empty())
1433                                         icp["before"] = from_utf8(opt1);
1434                                 string icstr = InsetCommandMailer::params2string("citation", icp);
1435                                 FuncRequest fr(LFUN_INSET_INSERT, icstr);
1436                                 dispatch(fr);
1437                         } else
1438                                 dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1439                         break;
1440                 }
1441
1442                 case LFUN_BUFFER_CHILD_OPEN: {
1443                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1444                         Buffer * parent = lyx_view_->buffer();
1445                         FileName filename = makeAbsPath(argument, parent->filePath());
1446                         view()->saveBookmark(false);
1447                         Buffer * child = 0;
1448                         bool parsed = false;
1449                         if (theBufferList().exists(filename.absFilename())) {
1450                                 child = theBufferList().getBuffer(filename.absFilename());
1451                         } else {
1452                                 setMessage(bformat(_("Opening child document %1$s..."),
1453                                         makeDisplayPath(filename.absFilename())));
1454                                 child = loadAndViewFile(filename, true);
1455                                 parsed = true;
1456                         }
1457                         if (child) {
1458                                 // Set the parent name of the child document.
1459                                 // This makes insertion of citations and references in the child work,
1460                                 // when the target is in the parent or another child document.
1461                                 child->setParentName(parent->absFileName());
1462                                 updateLabels(*child->masterBuffer());
1463                                 lyx_view_->setBuffer(child);
1464                                 if (parsed)
1465                                         child->errors("Parse");
1466                         }
1467
1468                         // If a screen update is required (in case where auto_open is false), 
1469                         // setBuffer() would have taken care of it already. Otherwise we shall 
1470                         // reset the update flag because it can cause a circular problem.
1471                         // See bug 3970.
1472                         updateFlags = Update::None;
1473                         break;
1474                 }
1475
1476                 case LFUN_TOGGLE_CURSOR_FOLLOWS_SCROLLBAR:
1477                         BOOST_ASSERT(lyx_view_);
1478                         lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1479                         break;
1480
1481                 case LFUN_KEYMAP_OFF:
1482                         BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1483                         lyx_view_->view()->getIntl().keyMapOn(false);
1484                         break;
1485
1486                 case LFUN_KEYMAP_PRIMARY:
1487                         BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1488                         lyx_view_->view()->getIntl().keyMapPrim();
1489                         break;
1490
1491                 case LFUN_KEYMAP_SECONDARY:
1492                         BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1493                         lyx_view_->view()->getIntl().keyMapSec();
1494                         break;
1495
1496                 case LFUN_KEYMAP_TOGGLE:
1497                         BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1498                         lyx_view_->view()->getIntl().toggleKeyMap();
1499                         break;
1500
1501                 case LFUN_REPEAT: {
1502                         // repeat command
1503                         string countstr;
1504                         string rest = split(argument, countstr, ' ');
1505                         istringstream is(countstr);
1506                         int count = 0;
1507                         is >> count;
1508                         lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1509                         for (int i = 0; i < count; ++i)
1510                                 dispatch(lyxaction.lookupFunc(rest));
1511                         break;
1512                 }
1513
1514                 case LFUN_COMMAND_SEQUENCE: {
1515                         // argument contains ';'-terminated commands
1516                         string arg = argument;
1517                         while (!arg.empty()) {
1518                                 string first;
1519                                 arg = split(arg, first, ';');
1520                                 FuncRequest func(lyxaction.lookupFunc(first));
1521                                 func.origin = cmd.origin;
1522                                 dispatch(func);
1523                         }
1524                         break;
1525                 }
1526
1527                 case LFUN_CALL: {
1528                         FuncRequest func;
1529                         if (LyX::ref().topLevelCmdDef().lock(argument, func)) {
1530                                 func.origin = cmd.origin;
1531                                 dispatch(func);
1532                                 LyX::ref().topLevelCmdDef().release(argument);
1533                         } else {
1534                                 if (func.action == LFUN_UNKNOWN_ACTION) {
1535                                         // unknown command definition
1536                                         lyxerr << "Warning: unknown command definition `"
1537                                                    << argument << "'"
1538                                                    << endl;
1539                                 } else {
1540                                         // recursion detected
1541                                         lyxerr << "Warning: Recursion in the command definition `"
1542                                                    << argument << "' detected"
1543                                                    << endl;
1544                                 }
1545                         }
1546                         break;
1547                 }
1548
1549                 case LFUN_PREFERENCES_SAVE: {
1550                         lyxrc.write(makeAbsPath("preferences",
1551                                                 package().user_support().absFilename()),
1552                                     false);
1553                         break;
1554                 }
1555
1556                 case LFUN_SET_COLOR: {
1557                         string lyx_name;
1558                         string const x11_name = split(argument, lyx_name, ' ');
1559                         if (lyx_name.empty() || x11_name.empty()) {
1560                                 setErrorMessage(from_ascii(N_(
1561                                                 "Syntax: set-color <lyx_name>"
1562                                                 " <x11_name>")));
1563                                 break;
1564                         }
1565
1566                         bool const graphicsbg_changed =
1567                                 (lyx_name == lcolor.getLyXName(Color_graphicsbg) &&
1568                                  x11_name != lcolor.getX11Name(Color_graphicsbg));
1569
1570                         if (!lcolor.setColor(lyx_name, x11_name)) {
1571                                 setErrorMessage(
1572                                                 bformat(_("Set-color \"%1$s\" failed "
1573                                                                        "- color is undefined or "
1574                                                                        "may not be redefined"),
1575                                                                            from_utf8(lyx_name)));
1576                                 break;
1577                         }
1578
1579                         theApp()->updateColor(lcolor.getFromLyXName(lyx_name));
1580
1581                         if (graphicsbg_changed) {
1582                                 // FIXME: The graphics cache no longer has a changeDisplay method.
1583 #if 0
1584                                 graphics::GCache::get().changeDisplay(true);
1585 #endif
1586                         }
1587                         break;
1588                 }
1589
1590                 case LFUN_MESSAGE:
1591                         BOOST_ASSERT(lyx_view_);
1592                         lyx_view_->message(from_utf8(argument));
1593                         break;
1594
1595                 case LFUN_EXTERNAL_EDIT: {
1596                         BOOST_ASSERT(lyx_view_);
1597                         FuncRequest fr(action, argument);
1598                         InsetExternal().dispatch(view()->cursor(), fr);
1599                         break;
1600                 }
1601
1602                 case LFUN_GRAPHICS_EDIT: {
1603                         FuncRequest fr(action, argument);
1604                         InsetGraphics().dispatch(view()->cursor(), fr);
1605                         break;
1606                 }
1607
1608                 case LFUN_ALL_INSETS_TOGGLE: {
1609                         BOOST_ASSERT(lyx_view_);
1610                         string action;
1611                         string const name = split(argument, action, ' ');
1612                         InsetCode const inset_code = insetCode(name);
1613
1614                         Cursor & cur = view()->cursor();
1615                         FuncRequest fr(LFUN_INSET_TOGGLE, action);
1616
1617                         Inset & inset = lyx_view_->buffer()->inset();
1618                         InsetIterator it  = inset_iterator_begin(inset);
1619                         InsetIterator const end = inset_iterator_end(inset);
1620                         for (; it != end; ++it) {
1621                                 if (!it->asInsetMath()
1622                                     && (inset_code == NO_CODE
1623                                     || inset_code == it->lyxCode())) {
1624                                         Cursor tmpcur = cur;
1625                                         tmpcur.pushBackward(*it);
1626                                         it->dispatch(tmpcur, fr);
1627                                 }
1628                         }
1629                         updateFlags = Update::Force | Update::FitCursor;
1630                         break;
1631                 }
1632
1633                 case LFUN_BUFFER_LANGUAGE: {
1634                         BOOST_ASSERT(lyx_view_);
1635                         Buffer & buffer = *lyx_view_->buffer();
1636                         Language const * oldL = buffer.params().language;
1637                         Language const * newL = languages.getLanguage(argument);
1638                         if (!newL || oldL == newL)
1639                                 break;
1640
1641                         if (oldL->rightToLeft() == newL->rightToLeft()
1642                             && !buffer.isMultiLingual())
1643                                 buffer.changeLanguage(oldL, newL);
1644                         break;
1645                 }
1646
1647                 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1648                         string const fname =
1649                                 addName(addPath(package().user_support().absFilename(), "templates/"),
1650                                         "defaults.lyx");
1651                         Buffer defaults(fname);
1652
1653                         istringstream ss(argument);
1654                         Lexer lex(0,0);
1655                         lex.setStream(ss);
1656                         int const unknown_tokens = defaults.readHeader(lex);
1657
1658                         if (unknown_tokens != 0) {
1659                                 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1660                                        << unknown_tokens << " unknown token"
1661                                        << (unknown_tokens == 1 ? "" : "s")
1662                                        << endl;
1663                         }
1664
1665                         if (defaults.writeFile(FileName(defaults.absFileName())))
1666                                 setMessage(bformat(_("Document defaults saved in %1$s"),
1667                                                    makeDisplayPath(fname)));
1668                         else
1669                                 setErrorMessage(from_ascii(N_("Unable to save document defaults")));
1670                         break;
1671                 }
1672
1673                 case LFUN_BUFFER_PARAMS_APPLY: {
1674                         BOOST_ASSERT(lyx_view_);
1675                         biblio::CiteEngine const oldEngine =
1676                                         lyx_view_->buffer()->params().getEngine();
1677                         
1678                         Buffer * buffer = lyx_view_->buffer();
1679
1680                         TextClassPtr oldClass = buffer->params().getTextClassPtr();
1681
1682                         Cursor & cur = view()->cursor();
1683                         cur.recordUndoFullDocument();
1684                         
1685                         istringstream ss(argument);
1686                         Lexer lex(0,0);
1687                         lex.setStream(ss);
1688                         int const unknown_tokens = buffer->readHeader(lex);
1689
1690                         if (unknown_tokens != 0) {
1691                                 lyxerr << "Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1692                                                 << unknown_tokens << " unknown token"
1693                                                 << (unknown_tokens == 1 ? "" : "s")
1694                                                 << endl;
1695                         }
1696                         
1697                         updateLayout(oldClass, buffer);
1698                         
1699                         biblio::CiteEngine const newEngine =
1700                                         lyx_view_->buffer()->params().getEngine();
1701                         
1702                         if (oldEngine != newEngine) {
1703                                 FuncRequest fr(LFUN_INSET_REFRESH);
1704         
1705                                 Inset & inset = lyx_view_->buffer()->inset();
1706                                 InsetIterator it  = inset_iterator_begin(inset);
1707                                 InsetIterator const end = inset_iterator_end(inset);
1708                                 for (; it != end; ++it)
1709                                         if (it->lyxCode() == CITE_CODE)
1710                                                 it->dispatch(cur, fr);
1711                         }
1712                         
1713                         updateFlags = Update::Force | Update::FitCursor;
1714                         break;
1715                 }
1716                 
1717                 case LFUN_LAYOUT_MODULES_CLEAR: {
1718                         BOOST_ASSERT(lyx_view_);
1719                         Buffer * buffer = lyx_view_->buffer();
1720                         TextClassPtr oldClass = buffer->params().getTextClassPtr();
1721                         view()->cursor().recordUndoFullDocument();
1722                         buffer->params().clearLayoutModules();
1723                         updateLayout(oldClass, buffer);
1724                         updateFlags = Update::Force | Update::FitCursor;
1725                         break;
1726                 }
1727                 
1728                 case LFUN_LAYOUT_MODULE_ADD: {
1729                         BOOST_ASSERT(lyx_view_);
1730                         Buffer * buffer = lyx_view_->buffer();
1731                         TextClassPtr oldClass = buffer->params().getTextClassPtr();
1732                         view()->cursor().recordUndoFullDocument();
1733                         buffer->params().addLayoutModule(argument);
1734                         updateLayout(oldClass, buffer);
1735                         updateFlags = Update::Force | Update::FitCursor;
1736                         break;
1737                 }
1738
1739                 case LFUN_TEXTCLASS_APPLY: {
1740                         BOOST_ASSERT(lyx_view_);
1741                         Buffer * buffer = lyx_view_->buffer();
1742
1743                         loadTextClass(argument);
1744
1745                         std::pair<bool, textclass_type> const tc_pair =
1746                                 textclasslist.numberOfClass(argument);
1747
1748                         if (!tc_pair.first)
1749                                 break;
1750
1751                         textclass_type const old_class = buffer->params().getBaseClass();
1752                         textclass_type const new_class = tc_pair.second;
1753
1754                         if (old_class == new_class)
1755                                 // nothing to do
1756                                 break;
1757
1758                         //Save the old, possibly modular, layout for use in conversion.
1759                         TextClassPtr oldClass = buffer->params().getTextClassPtr();
1760                         view()->cursor().recordUndoFullDocument();
1761                         buffer->params().setBaseClass(new_class);
1762                         updateLayout(oldClass, buffer);
1763                         updateFlags = Update::Force | Update::FitCursor;
1764                         break;
1765                 }
1766                 
1767                 case LFUN_LAYOUT_RELOAD: {
1768                         BOOST_ASSERT(lyx_view_);
1769                         Buffer * buffer = lyx_view_->buffer();
1770                         TextClassPtr oldClass = buffer->params().getTextClassPtr();
1771                         textclass_type const tc = buffer->params().getBaseClass();
1772                         textclasslist.reset(tc);
1773                         buffer->params().setBaseClass(tc);
1774                         updateLayout(oldClass, buffer);
1775                         updateFlags = Update::Force | Update::FitCursor;
1776                         break;
1777                 }
1778
1779                 case LFUN_TEXTCLASS_LOAD:
1780                         loadTextClass(argument);
1781                         break;
1782
1783                 case LFUN_LYXRC_APPLY: {
1784                         LyXRC const lyxrc_orig = lyxrc;
1785
1786                         istringstream ss(argument);
1787                         bool const success = lyxrc.read(ss) == 0;
1788
1789                         if (!success) {
1790                                 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1791                                        << "Unable to read lyxrc data"
1792                                        << endl;
1793                                 break;
1794                         }
1795
1796                         actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1797
1798                         theApp()->resetGui();
1799
1800                         /// We force the redraw in any case because there might be
1801                         /// some screen font changes.
1802                         /// FIXME: only the current view will be updated. the Gui
1803                         /// class is able to furnish the list of views.
1804                         updateFlags = Update::Force;
1805                         break;
1806                 }
1807
1808                 case LFUN_BOOKMARK_GOTO:
1809                         // go to bookmark, open unopened file and switch to buffer if necessary
1810                         gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1811                         break;
1812
1813                 case LFUN_BOOKMARK_CLEAR:
1814                         LyX::ref().session().bookmarks().clear();
1815                         break;
1816
1817                 default: {
1818                         BOOST_ASSERT(theApp());
1819                         // Let the frontend dispatch its own actions.
1820                         if (theApp()->dispatch(cmd))
1821                                 // Nothing more to do.
1822                                 return;
1823
1824                         // Let the current LyXView dispatch its own actions.
1825                         BOOST_ASSERT(lyx_view_);
1826                         if (lyx_view_->dispatch(cmd, false)) {
1827                                 if (lyx_view_->view())
1828                                         updateFlags = lyx_view_->view()->cursor().result().update();
1829                                 break;
1830                         }
1831
1832                         // FIXME: Probably a good idea to inverse the Cursor and BufferView
1833                         // dispatching.
1834
1835                         // Let the current Cursor dispatch its own actions.
1836                         BOOST_ASSERT(lyx_view_->view());
1837                         view()->cursor().dispatch(cmd);
1838                         updateFlags = view()->cursor().result().update();
1839                         if (!view()->cursor().result().dispatched())
1840                                 // Let the current BufferView dispatch its own actions.
1841                                 updateFlags = view()->dispatch(cmd);
1842                         break;
1843                 }
1844                 }
1845
1846                 if (lyx_view_ && lyx_view_->buffer()) {
1847                         // BufferView::update() updates the ViewMetricsInfo and
1848                         // also initializes the position cache for all insets in
1849                         // (at least partially) visible top-level paragraphs.
1850                         // We will redraw the screen only if needed.
1851                         view()->processUpdateFlags(updateFlags);
1852
1853                         // if we executed a mutating lfun, mark the buffer as dirty
1854                         if (flag.enabled()
1855                             && !lyxaction.funcHasFlag(action, LyXAction::NoBuffer)
1856                             && !lyxaction.funcHasFlag(action, LyXAction::ReadOnly))
1857                                 lyx_view_->buffer()->markDirty();
1858
1859                         //Do we have a selection?
1860                         theSelection().haveSelection(view()->cursor().selection());
1861                 }
1862         }
1863         if (!quitting && lyx_view_) {
1864                 // Some messages may already be translated, so we cannot use _()
1865                 sendDispatchMessage(translateIfPossible(getMessage()), cmd);
1866         }
1867 }
1868
1869
1870 void LyXFunc::sendDispatchMessage(docstring const & msg, FuncRequest const & cmd)
1871 {
1872         const bool verbose = (cmd.origin == FuncRequest::MENU
1873                               || cmd.origin == FuncRequest::TOOLBAR
1874                               || cmd.origin == FuncRequest::COMMANDBUFFER);
1875
1876         if (cmd.action == LFUN_SELF_INSERT || !verbose) {
1877                 LYXERR(Debug::ACTION, "dispatch msg is " << to_utf8(msg));
1878                 if (!msg.empty())
1879                         lyx_view_->message(msg);
1880                 return;
1881         }
1882
1883         docstring dispatch_msg = msg;
1884         if (!dispatch_msg.empty())
1885                 dispatch_msg += ' ';
1886
1887         docstring comname = from_utf8(lyxaction.getActionName(cmd.action));
1888
1889         bool argsadded = false;
1890
1891         if (!cmd.argument().empty()) {
1892                 if (cmd.action != LFUN_UNKNOWN_ACTION) {
1893                         comname += ' ' + cmd.argument();
1894                         argsadded = true;
1895                 }
1896         }
1897
1898         docstring const shortcuts = theTopLevelKeymap().printBindings(cmd);
1899
1900         if (!shortcuts.empty())
1901                 comname += ": " + shortcuts;
1902         else if (!argsadded && !cmd.argument().empty())
1903                 comname += ' ' + cmd.argument();
1904
1905         if (!comname.empty()) {
1906                 comname = rtrim(comname);
1907                 dispatch_msg += '(' + rtrim(comname) + ')';
1908         }
1909
1910         LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1911         if (!dispatch_msg.empty())
1912                 lyx_view_->message(dispatch_msg);
1913 }
1914
1915
1916 void LyXFunc::menuNew(string const & name, bool fromTemplate)
1917 {
1918         // FIXME: initpath is not used. What to do?
1919         string initpath = lyxrc.document_path;
1920         string filename(name);
1921
1922         if (lyx_view_->buffer()) {
1923                 string const trypath = lyx_view_->buffer()->filePath();
1924                 // If directory is writeable, use this as default.
1925                 if (FileName(trypath).isDirWritable())
1926                         initpath = trypath;
1927         }
1928
1929         static int newfile_number;
1930
1931         if (filename.empty()) {
1932                 filename = addName(lyxrc.document_path,
1933                             "newfile" + convert<string>(++newfile_number) + ".lyx");
1934                 while (theBufferList().exists(filename) ||
1935                        FileName(filename).isReadableFile()) {
1936                         ++newfile_number;
1937                         filename = addName(lyxrc.document_path,
1938                                            "newfile" +  convert<string>(newfile_number) +
1939                                     ".lyx");
1940                 }
1941         }
1942
1943         // The template stuff
1944         string templname;
1945         if (fromTemplate) {
1946                 FileDialog dlg(_("Select template file"));
1947                 dlg.setButton1(_("Documents|#o#O"), from_utf8(lyxrc.document_path));
1948                 dlg.setButton1(_("Templates|#T#t"), from_utf8(lyxrc.template_path));
1949
1950                 FileDialog::Result result =
1951                         dlg.open(from_utf8(lyxrc.template_path),
1952                                      FileFilterList(_("LyX Documents (*.lyx)")),
1953                                      docstring());
1954
1955                 if (result.first == FileDialog::Later)
1956                         return;
1957                 if (result.second.empty())
1958                         return;
1959                 templname = to_utf8(result.second);
1960         }
1961
1962         Buffer * const b = newFile(filename, templname, !name.empty());
1963         if (b)
1964                 lyx_view_->setBuffer(b);
1965 }
1966
1967
1968 Buffer * LyXFunc::loadAndViewFile(FileName const & filename, bool tolastfiles)
1969 {
1970         lyx_view_->setBusy(true);
1971
1972         Buffer * newBuffer = checkAndLoadLyXFile(filename);
1973
1974         if (!newBuffer) {
1975                 lyx_view_->message(_("Document not loaded."));
1976                 lyx_view_->setBusy(false);
1977                 return 0;
1978         }
1979
1980         lyx_view_->setBuffer(newBuffer);
1981
1982         // scroll to the position when the file was last closed
1983         if (lyxrc.use_lastfilepos) {
1984                 LastFilePosSection::FilePos filepos =
1985                         LyX::ref().session().lastFilePos().load(filename);
1986                 lyx_view_->view()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1987         }
1988
1989         if (tolastfiles)
1990                 LyX::ref().session().lastFiles().add(filename);
1991
1992         lyx_view_->setBusy(false);
1993         return newBuffer;
1994 }
1995
1996
1997 void LyXFunc::open(string const & fname)
1998 {
1999         string initpath = lyxrc.document_path;
2000
2001         if (lyx_view_->buffer()) {
2002                 string const trypath = lyx_view_->buffer()->filePath();
2003                 // If directory is writeable, use this as default.
2004                 if (FileName(trypath).isDirWritable())
2005                         initpath = trypath;
2006         }
2007
2008         string filename;
2009
2010         if (fname.empty()) {
2011                 FileDialog dlg(_("Select document to open"), LFUN_FILE_OPEN);
2012                 dlg.setButton1(_("Documents|#o#O"), from_utf8(lyxrc.document_path));
2013                 dlg.setButton2(_("Examples|#E#e"),
2014                                 from_utf8(addPath(package().system_support().absFilename(), "examples")));
2015
2016                 FileDialog::Result result =
2017                         dlg.open(from_utf8(initpath),
2018                                      FileFilterList(_("LyX Documents (*.lyx)")),
2019                                      docstring());
2020
2021                 if (result.first == FileDialog::Later)
2022                         return;
2023
2024                 filename = to_utf8(result.second);
2025
2026                 // check selected filename
2027                 if (filename.empty()) {
2028                         lyx_view_->message(_("Canceled."));
2029                         return;
2030                 }
2031         } else
2032                 filename = fname;
2033
2034         // get absolute path of file and add ".lyx" to the filename if
2035         // necessary
2036         FileName const fullname = fileSearch(string(), filename, "lyx");
2037         if (!fullname.empty())
2038                 filename = fullname.absFilename();
2039
2040         // if the file doesn't exist, let the user create one
2041         if (!fullname.exists()) {
2042                 // the user specifically chose this name. Believe him.
2043                 Buffer * const b = newFile(filename, string(), true);
2044                 if (b)
2045                         lyx_view_->setBuffer(b);
2046                 return;
2047         }
2048
2049         docstring const disp_fn = makeDisplayPath(filename);
2050         lyx_view_->message(bformat(_("Opening document %1$s..."), disp_fn));
2051
2052         docstring str2;
2053         Buffer * buf = loadAndViewFile(fullname);
2054         if (buf) {
2055                 updateLabels(*buf);
2056                 lyx_view_->setBuffer(buf);
2057                 buf->errors("Parse");
2058                 str2 = bformat(_("Document %1$s opened."), disp_fn);
2059         } else {
2060                 str2 = bformat(_("Could not open document %1$s"), disp_fn);
2061         }
2062         lyx_view_->message(str2);
2063 }
2064
2065
2066 void LyXFunc::doImport(string const & argument)
2067 {
2068         string format;
2069         string filename = split(argument, format, ' ');
2070
2071         LYXERR(Debug::INFO, "LyXFunc::doImport: " << format
2072                             << " file: " << filename);
2073
2074         // need user interaction
2075         if (filename.empty()) {
2076                 string initpath = lyxrc.document_path;
2077
2078                 if (lyx_view_->buffer()) {
2079                         string const trypath = lyx_view_->buffer()->filePath();
2080                         // If directory is writeable, use this as default.
2081                         if (FileName(trypath).isDirWritable())
2082                                 initpath = trypath;
2083                 }
2084
2085                 docstring const text = bformat(_("Select %1$s file to import"),
2086                         formats.prettyName(format));
2087
2088                 FileDialog dlg(text, LFUN_BUFFER_IMPORT);
2089                 dlg.setButton1(_("Documents|#o#O"), from_utf8(lyxrc.document_path));
2090                 dlg.setButton2(_("Examples|#E#e"),
2091                         from_utf8(addPath(package().system_support().absFilename(), "examples")));
2092
2093                 docstring filter = formats.prettyName(format);
2094                 filter += " (*.";
2095                 // FIXME UNICODE
2096                 filter += from_utf8(formats.extension(format));
2097                 filter += ')';
2098
2099                 FileDialog::Result result =
2100                         dlg.open(from_utf8(initpath),
2101                                      FileFilterList(filter),
2102                                      docstring());
2103
2104                 if (result.first == FileDialog::Later)
2105                         return;
2106
2107                 filename = to_utf8(result.second);
2108
2109                 // check selected filename
2110                 if (filename.empty())
2111                         lyx_view_->message(_("Canceled."));
2112         }
2113
2114         if (filename.empty())
2115                 return;
2116
2117         // get absolute path of file
2118         FileName const fullname(makeAbsPath(filename));
2119
2120         FileName const lyxfile(changeExtension(fullname.absFilename(), ".lyx"));
2121
2122         // Check if the document already is open
2123         if (use_gui && theBufferList().exists(lyxfile.absFilename())) {
2124                 if (!theBufferList().close(theBufferList().getBuffer(lyxfile.absFilename()), true)) {
2125                         lyx_view_->message(_("Canceled."));
2126                         return;
2127                 }
2128         }
2129
2130         // if the file exists already, and we didn't do
2131         // -i lyx thefile.lyx, warn
2132         if (lyxfile.exists() && fullname != lyxfile) {
2133                 docstring const file = makeDisplayPath(lyxfile.absFilename(), 30);
2134
2135                 docstring text = bformat(_("The document %1$s already exists.\n\n"
2136                                                      "Do you want to overwrite that document?"), file);
2137                 int const ret = Alert::prompt(_("Overwrite document?"),
2138                         text, 0, 1, _("&Overwrite"), _("&Cancel"));
2139
2140                 if (ret == 1) {
2141                         lyx_view_->message(_("Canceled."));
2142                         return;
2143                 }
2144         }
2145
2146         ErrorList errorList;
2147         import(lyx_view_, fullname, format, errorList);
2148         // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2149 }
2150
2151
2152 void LyXFunc::closeBuffer()
2153 {
2154         // goto bookmark to update bookmark pit.
2155         for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i)
2156                 gotoBookmark(i+1, false, false);
2157         
2158         theBufferList().close(lyx_view_->buffer(), true);
2159 }
2160
2161
2162 void LyXFunc::reloadBuffer()
2163 {
2164         FileName filename(lyx_view_->buffer()->absFileName());
2165         docstring const disp_fn = makeDisplayPath(filename.absFilename());
2166         docstring str;
2167         closeBuffer();
2168         Buffer * buf = loadAndViewFile(filename);
2169         if (buf) {
2170                 updateLabels(*buf);
2171                 lyx_view_->setBuffer(buf);
2172                 buf->errors("Parse");
2173                 str = bformat(_("Document %1$s reloaded."), disp_fn);
2174         } else {
2175                 str = bformat(_("Could not reload document %1$s"), disp_fn);
2176         }
2177         lyx_view_->message(str);
2178 }
2179
2180 // Each "lyx_view_" should have it's own message method. lyxview and
2181 // the minibuffer would use the minibuffer, but lyxserver would
2182 // send an ERROR signal to its client.  Alejandro 970603
2183 // This function is bit problematic when it comes to NLS, to make the
2184 // lyx servers client be language indepenent we must not translate
2185 // strings sent to this func.
2186 void LyXFunc::setErrorMessage(docstring const & m) const
2187 {
2188         dispatch_buffer = m;
2189         errorstat = true;
2190 }
2191
2192
2193 void LyXFunc::setMessage(docstring const & m) const
2194 {
2195         dispatch_buffer = m;
2196 }
2197
2198
2199 docstring const LyXFunc::viewStatusMessage()
2200 {
2201         // When meta-fake key is pressed, show the key sequence so far + "M-".
2202         if (wasMetaKey())
2203                 return keyseq.print(KeySequence::ForGui) + "M-";
2204
2205         // Else, when a non-complete key sequence is pressed,
2206         // show the available options.
2207         if (keyseq.length() > 0 && !keyseq.deleted())
2208                 return keyseq.printOptions(true);
2209
2210         BOOST_ASSERT(lyx_view_);
2211         if (!lyx_view_->buffer())
2212                 return _("Welcome to LyX!");
2213
2214         return view()->cursor().currentState();
2215 }
2216
2217
2218 BufferView * LyXFunc::view() const
2219 {
2220         BOOST_ASSERT(lyx_view_);
2221         return lyx_view_->view();
2222 }
2223
2224
2225 bool LyXFunc::wasMetaKey() const
2226 {
2227         return (meta_fake_bit != NoModifier);
2228 }
2229
2230
2231 void LyXFunc::updateLayout(TextClassPtr const & oldlayout,
2232                            Buffer * buffer)
2233 {
2234         lyx_view_->message(_("Converting document to new document class..."));
2235         
2236         StableDocIterator backcur(view()->cursor());
2237         ErrorList & el = buffer->errorList("Class Switch");
2238         cap::switchBetweenClasses(
2239                         oldlayout, buffer->params().getTextClassPtr(),
2240                         static_cast<InsetText &>(buffer->inset()), el);
2241
2242         view()->setCursor(backcur.asDocIterator(&(buffer->inset())));
2243
2244         buffer->errors("Class Switch");
2245         updateLabels(*buffer);
2246 }
2247
2248
2249 namespace {
2250
2251 void actOnUpdatedPrefs(LyXRC const & lyxrc_orig, LyXRC const & lyxrc_new)
2252 {
2253         // Why the switch you might ask. It is a trick to ensure that all
2254         // the elements in the LyXRCTags enum is handled. As you can see
2255         // there are no breaks at all. So it is just a huge fall-through.
2256         // The nice thing is that we will get a warning from the compiler
2257         // if we forget an element.
2258         LyXRC::LyXRCTags tag = LyXRC::RC_LAST;
2259         switch (tag) {
2260         case LyXRC::RC_ACCEPT_COMPOUND:
2261         case LyXRC::RC_ALT_LANG:
2262         case LyXRC::RC_PLAINTEXT_ROFF_COMMAND:
2263         case LyXRC::RC_PLAINTEXT_LINELEN:
2264         case LyXRC::RC_AUTOREGIONDELETE:
2265         case LyXRC::RC_AUTORESET_OPTIONS:
2266         case LyXRC::RC_AUTOSAVE:
2267         case LyXRC::RC_AUTO_NUMBER:
2268         case LyXRC::RC_BACKUPDIR_PATH:
2269         case LyXRC::RC_BIBTEX_COMMAND:
2270         case LyXRC::RC_BINDFILE:
2271         case LyXRC::RC_CHECKLASTFILES:
2272         case LyXRC::RC_USELASTFILEPOS:
2273         case LyXRC::RC_LOADSESSION:
2274         case LyXRC::RC_CHKTEX_COMMAND:
2275         case LyXRC::RC_CONVERTER:
2276         case LyXRC::RC_CONVERTER_CACHE_MAXAGE:
2277         case LyXRC::RC_COPIER:
2278         case LyXRC::RC_CURSOR_FOLLOWS_SCROLLBAR:
2279         case LyXRC::RC_CUSTOM_EXPORT_COMMAND:
2280         case LyXRC::RC_CUSTOM_EXPORT_FORMAT:
2281         case LyXRC::RC_DATE_INSERT_FORMAT:
2282         case LyXRC::RC_DEFAULT_LANGUAGE:
2283         case LyXRC::RC_DEFAULT_PAPERSIZE:
2284         case LyXRC::RC_DEFFILE:
2285         case LyXRC::RC_DIALOGS_ICONIFY_WITH_MAIN:
2286         case LyXRC::RC_DISPLAY_GRAPHICS:
2287         case LyXRC::RC_DOCUMENTPATH:
2288                 if (lyxrc_orig.document_path != lyxrc_new.document_path) {
2289                         FileName path(lyxrc_new.document_path);
2290                         if (path.exists() && path.isDirectory())
2291                                 support::package().document_dir() = FileName(lyxrc.document_path);
2292                 }
2293         case LyXRC::RC_ESC_CHARS:
2294         case LyXRC::RC_FONT_ENCODING:
2295         case LyXRC::RC_FORMAT:
2296         case LyXRC::RC_INDEX_COMMAND:
2297         case LyXRC::RC_INPUT:
2298         case LyXRC::RC_KBMAP:
2299         case LyXRC::RC_KBMAP_PRIMARY:
2300         case LyXRC::RC_KBMAP_SECONDARY:
2301         case LyXRC::RC_LABEL_INIT_LENGTH:
2302         case LyXRC::RC_LANGUAGE_AUTO_BEGIN:
2303         case LyXRC::RC_LANGUAGE_AUTO_END:
2304         case LyXRC::RC_LANGUAGE_COMMAND_BEGIN:
2305         case LyXRC::RC_LANGUAGE_COMMAND_END:
2306         case LyXRC::RC_LANGUAGE_COMMAND_LOCAL:
2307         case LyXRC::RC_LANGUAGE_GLOBAL_OPTIONS:
2308         case LyXRC::RC_LANGUAGE_PACKAGE:
2309         case LyXRC::RC_LANGUAGE_USE_BABEL:
2310         case LyXRC::RC_MAKE_BACKUP:
2311         case LyXRC::RC_MARK_FOREIGN_LANGUAGE:
2312         case LyXRC::RC_NUMLASTFILES:
2313         case LyXRC::RC_PATH_PREFIX:
2314                 if (lyxrc_orig.path_prefix != lyxrc_new.path_prefix) {
2315                         support::prependEnvPath("PATH", lyxrc.path_prefix);
2316                 }
2317         case LyXRC::RC_PERS_DICT:
2318         case LyXRC::RC_PREVIEW:
2319         case LyXRC::RC_PREVIEW_HASHED_LABELS:
2320         case LyXRC::RC_PREVIEW_SCALE_FACTOR:
2321         case LyXRC::RC_PRINTCOLLCOPIESFLAG:
2322         case LyXRC::RC_PRINTCOPIESFLAG:
2323         case LyXRC::RC_PRINTER:
2324         case LyXRC::RC_PRINTEVENPAGEFLAG:
2325         case LyXRC::RC_PRINTEXSTRAOPTIONS:
2326         case LyXRC::RC_PRINTFILEEXTENSION:
2327         case LyXRC::RC_PRINTLANDSCAPEFLAG:
2328         case LyXRC::RC_PRINTODDPAGEFLAG:
2329         case LyXRC::RC_PRINTPAGERANGEFLAG:
2330         case LyXRC::RC_PRINTPAPERDIMENSIONFLAG:
2331         case LyXRC::RC_PRINTPAPERFLAG:
2332         case LyXRC::RC_PRINTREVERSEFLAG:
2333         case LyXRC::RC_PRINTSPOOL_COMMAND:
2334         case LyXRC::RC_PRINTSPOOL_PRINTERPREFIX:
2335         case LyXRC::RC_PRINTTOFILE:
2336         case LyXRC::RC_PRINTTOPRINTER:
2337         case LyXRC::RC_PRINT_ADAPTOUTPUT:
2338         case LyXRC::RC_PRINT_COMMAND:
2339         case LyXRC::RC_RTL_SUPPORT:
2340         case LyXRC::RC_SCREEN_DPI:
2341         case LyXRC::RC_SCREEN_FONT_ROMAN:
2342         case LyXRC::RC_SCREEN_FONT_ROMAN_FOUNDRY:
2343         case LyXRC::RC_SCREEN_FONT_SANS:
2344         case LyXRC::RC_SCREEN_FONT_SANS_FOUNDRY:
2345         case LyXRC::RC_SCREEN_FONT_SCALABLE:
2346         case LyXRC::RC_SCREEN_FONT_SIZES:
2347         case LyXRC::RC_SCREEN_FONT_TYPEWRITER:
2348         case LyXRC::RC_SCREEN_FONT_TYPEWRITER_FOUNDRY:
2349         case LyXRC::RC_GEOMETRY_SESSION:
2350         case LyXRC::RC_SCREEN_ZOOM:
2351         case LyXRC::RC_SERVERPIPE:
2352         case LyXRC::RC_SET_COLOR:
2353         case LyXRC::RC_SHOW_BANNER:
2354         case LyXRC::RC_SPELL_COMMAND:
2355         case LyXRC::RC_TEMPDIRPATH:
2356         case LyXRC::RC_TEMPLATEPATH:
2357         case LyXRC::RC_TEX_ALLOWS_SPACES:
2358         case LyXRC::RC_TEX_EXPECTS_WINDOWS_PATHS:
2359                 if (lyxrc_orig.windows_style_tex_paths != lyxrc_new.windows_style_tex_paths) {
2360                         support::os::windows_style_tex_paths(lyxrc_new.windows_style_tex_paths);
2361                 }
2362         case LyXRC::RC_UIFILE:
2363         case LyXRC::RC_USER_EMAIL:
2364         case LyXRC::RC_USER_NAME:
2365         case LyXRC::RC_USETEMPDIR:
2366         case LyXRC::RC_USE_ALT_LANG:
2367         case LyXRC::RC_USE_CONVERTER_CACHE:
2368         case LyXRC::RC_USE_ESC_CHARS:
2369         case LyXRC::RC_USE_INP_ENC:
2370         case LyXRC::RC_USE_PERS_DICT:
2371         case LyXRC::RC_USE_PIXMAP_CACHE:
2372         case LyXRC::RC_USE_SPELL_LIB:
2373         case LyXRC::RC_VIEWDVI_PAPEROPTION:
2374         case LyXRC::RC_SORT_LAYOUTS:
2375         case LyXRC::RC_VIEWER:
2376         case LyXRC::RC_LAST:
2377                 break;
2378         }
2379 }
2380
2381 } // namespace anon
2382
2383
2384 } // namespace lyx