]> git.lyx.org Git - lyx.git/blob - src/LyXFunc.cpp
* support/FileName:
[lyx.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));
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                 // Let the frontend dispatch its own actions.
851                 case LFUN_WINDOW_NEW:
852                 case LFUN_WINDOW_CLOSE:
853                 case LFUN_LYX_QUIT:
854                         BOOST_ASSERT(theApp());
855                         theApp()->dispatch(cmd);
856                         // Nothing more to do.
857                         return;
858
859                 // Let lyx_view_ dispatch its own actions.
860                 case LFUN_BUFFER_SWITCH:
861                 case LFUN_BUFFER_NEXT:
862                 case LFUN_BUFFER_PREVIOUS:
863                 case LFUN_COMMAND_EXECUTE:
864                 case LFUN_DROP_LAYOUTS_CHOICE:
865                 case LFUN_MENU_OPEN:
866                 case LFUN_TOOLBAR_TOGGLE:
867                 case LFUN_DIALOG_UPDATE:
868                 case LFUN_DIALOG_TOGGLE:
869                 case LFUN_DIALOG_DISCONNECT_INSET:
870                 case LFUN_DIALOG_HIDE:
871                 case LFUN_DIALOG_SHOW:
872                 case LFUN_INSET_APPLY:
873                         BOOST_ASSERT(lyx_view_);
874                         lyx_view_->dispatch(cmd);
875                         if (lyx_view_->view())
876                                 updateFlags = lyx_view_->view()->cursor().result().update();
877                         break;
878
879                 case LFUN_WORD_FIND_FORWARD:
880                 case LFUN_WORD_FIND_BACKWARD: {
881                         BOOST_ASSERT(lyx_view_ && lyx_view_->view());
882                         static docstring last_search;
883                         docstring searched_string;
884
885                         if (!cmd.argument().empty()) {
886                                 last_search = cmd.argument();
887                                 searched_string = cmd.argument();
888                         } else {
889                                 searched_string = last_search;
890                         }
891
892                         if (searched_string.empty())
893                                 break;
894
895                         bool const fw = action == LFUN_WORD_FIND_FORWARD;
896                         docstring const data =
897                                 find2string(searched_string, true, false, fw);
898                         find(view(), FuncRequest(LFUN_WORD_FIND, data));
899                         break;
900                 }
901
902                 case LFUN_COMMAND_PREFIX:
903                         BOOST_ASSERT(lyx_view_);
904                         lyx_view_->message(keyseq.printOptions(true));
905                         break;
906
907                 case LFUN_CANCEL:
908                         BOOST_ASSERT(lyx_view_ && lyx_view_->view());
909                         keyseq.reset();
910                         meta_fake_bit = NoModifier;
911                         if (lyx_view_->buffer())
912                                 // cancel any selection
913                                 dispatch(FuncRequest(LFUN_MARK_OFF));
914                         setMessage(from_ascii(N_("Cancel")));
915                         break;
916
917                 case LFUN_META_PREFIX:
918                         meta_fake_bit = AltModifier;
919                         setMessage(keyseq.print(KeySequence::ForGui));
920                         break;
921
922                 case LFUN_BUFFER_TOGGLE_READ_ONLY: {
923                         BOOST_ASSERT(lyx_view_ && lyx_view_->view() && lyx_view_->buffer());
924                         Buffer * buf = lyx_view_->buffer();
925                         if (buf->lyxvc().inUse())
926                                 buf->lyxvc().toggleReadOnly();
927                         else
928                                 buf->setReadonly(!lyx_view_->buffer()->isReadonly());
929                         break;
930                 }
931
932                 // --- Menus -----------------------------------------------
933                 case LFUN_BUFFER_NEW:
934                         menuNew(argument, false);
935                         updateFlags = Update::None;
936                         break;
937
938                 case LFUN_BUFFER_NEW_TEMPLATE:
939                         menuNew(argument, true);
940                         updateFlags = Update::None;
941                         break;
942
943                 case LFUN_BUFFER_CLOSE:
944                         closeBuffer();
945                         updateFlags = Update::None;
946                         break;
947
948                 case LFUN_BUFFER_WRITE:
949                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
950                         if (!lyx_view_->buffer()->isUnnamed()) {
951                                 docstring const str = bformat(_("Saving document %1$s..."),
952                                          makeDisplayPath(lyx_view_->buffer()->absFileName()));
953                                 lyx_view_->message(str);
954                                 lyx_view_->buffer()->menuWrite();
955                                 lyx_view_->message(str + _(" done."));
956                         } else {
957                                 lyx_view_->buffer()->writeAs();
958                         }
959                         updateFlags = Update::None;
960                         break;
961
962                 case LFUN_BUFFER_WRITE_AS:
963                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
964                         lyx_view_->buffer()->writeAs(argument);
965                         updateFlags = Update::None;
966                         break;
967
968                 case LFUN_BUFFER_WRITE_ALL: {
969                         Buffer * first = theBufferList().first();
970                         if (first) {
971                                 Buffer * b = first;
972                                 lyx_view_->message(_("Saving all documents..."));
973                 
974                                 // We cannot use a for loop as the buffer list cycles.
975                                 do {
976                                         if (!b->isClean()) {
977                                                 if (!b->isUnnamed()) {
978                                                         b->menuWrite();
979                                                         lyxerr[Debug::ACTION] << "Saved " << b->absFileName() << endl;
980                                                 } else
981                                                         b->writeAs();
982                                         }
983                                         b = theBufferList().next(b);
984                                 } while (b != first); 
985                                 lyx_view_->message(_("All documents saved."));
986                         } 
987         
988                         updateFlags = Update::None;
989                         break;
990                 }
991
992                 case LFUN_BUFFER_RELOAD: {
993                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
994                         docstring const file = makeDisplayPath(lyx_view_->buffer()->absFileName(), 20);
995                         docstring text = bformat(_("Any changes will be lost. Are you sure "
996                                                              "you want to revert to the saved version of the document %1$s?"), file);
997                         int const ret = Alert::prompt(_("Revert to saved document?"),
998                                 text, 1, 1, _("&Revert"), _("&Cancel"));
999
1000                         if (ret == 0)
1001                                 reloadBuffer();
1002                         break;
1003                 }
1004
1005                 case LFUN_BUFFER_UPDATE:
1006                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1007                         lyx_view_->buffer()->doExport(argument, true);
1008                         break;
1009
1010                 case LFUN_BUFFER_VIEW:
1011                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1012                         lyx_view_->buffer()->preview(argument);
1013                         break;
1014
1015                 case LFUN_MASTER_BUFFER_UPDATE:
1016                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer() && lyx_view_->buffer()->masterBuffer());
1017                         lyx_view_->buffer()->masterBuffer()->doExport(argument, true);
1018                         break;
1019
1020                 case LFUN_MASTER_BUFFER_VIEW:
1021                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer() && lyx_view_->buffer()->masterBuffer());
1022                         lyx_view_->buffer()->masterBuffer()->preview(argument);
1023                         break;
1024
1025                 case LFUN_BUILD_PROGRAM:
1026                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1027                         lyx_view_->buffer()->doExport("program", true);
1028                         break;
1029
1030                 case LFUN_BUFFER_CHKTEX:
1031                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1032                         lyx_view_->buffer()->runChktex();
1033                         break;
1034
1035                 case LFUN_BUFFER_EXPORT:
1036                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1037                         if (argument == "custom")
1038                                 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"));
1039                         else
1040                                 lyx_view_->buffer()->doExport(argument, false);
1041                         break;
1042
1043                 case LFUN_BUFFER_EXPORT_CUSTOM: {
1044                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1045                         string format_name;
1046                         string command = split(argument, format_name, ' ');
1047                         Format const * format = formats.getFormat(format_name);
1048                         if (!format) {
1049                                 lyxerr << "Format \"" << format_name
1050                                        << "\" not recognized!"
1051                                        << std::endl;
1052                                 break;
1053                         }
1054
1055                         Buffer * buffer = lyx_view_->buffer();
1056
1057                         // The name of the file created by the conversion process
1058                         string filename;
1059
1060                         // Output to filename
1061                         if (format->name() == "lyx") {
1062                                 string const latexname = buffer->latexName(false);
1063                                 filename = changeExtension(latexname,
1064                                                            format->extension());
1065                                 filename = addName(buffer->temppath(), filename);
1066
1067                                 if (!buffer->writeFile(FileName(filename)))
1068                                         break;
1069
1070                         } else {
1071                                 buffer->doExport(format_name, true, filename);
1072                         }
1073
1074                         // Substitute $$FName for filename
1075                         if (!contains(command, "$$FName"))
1076                                 command = "( " + command + " ) < $$FName";
1077                         command = subst(command, "$$FName", filename);
1078
1079                         // Execute the command in the background
1080                         Systemcall call;
1081                         call.startscript(Systemcall::DontWait, command);
1082                         break;
1083                 }
1084
1085                 case LFUN_BUFFER_PRINT: {
1086                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1087                         // FIXME: cmd.getArg() might fail if one of the arguments
1088                         // contains double quotes
1089                         string target = cmd.getArg(0);
1090                         string target_name = cmd.getArg(1);
1091                         string command = cmd.getArg(2);
1092
1093                         if (target.empty()
1094                             || target_name.empty()
1095                             || command.empty()) {
1096                                 lyxerr << "Unable to parse \""
1097                                        << argument << '"' << endl;
1098                                 break;
1099                         }
1100                         if (target != "printer" && target != "file") {
1101                                 lyxerr << "Unrecognized target \""
1102                                        << target << '"' << endl;
1103                                 break;
1104                         }
1105
1106                         Buffer * buffer = lyx_view_->buffer();
1107
1108                         if (!buffer->doExport("dvi", true)) {
1109                                 showPrintError(buffer->absFileName());
1110                                 break;
1111                         }
1112
1113                         // Push directory path.
1114                         string const path = buffer->temppath();
1115                         // Prevent the compiler from optimizing away p
1116                         FileName pp(path);
1117                         support::PathChanger p(pp);
1118
1119                         // there are three cases here:
1120                         // 1. we print to a file
1121                         // 2. we print directly to a printer
1122                         // 3. we print using a spool command (print to file first)
1123                         Systemcall one;
1124                         int res = 0;
1125                         string const dviname =
1126                                 changeExtension(buffer->latexName(true), "dvi");
1127
1128                         if (target == "printer") {
1129                                 if (!lyxrc.print_spool_command.empty()) {
1130                                         // case 3: print using a spool
1131                                         string const psname =
1132                                                 changeExtension(dviname,".ps");
1133                                         command += ' ' + lyxrc.print_to_file
1134                                                 + quoteName(psname)
1135                                                 + ' '
1136                                                 + quoteName(dviname);
1137
1138                                         string command2 =
1139                                                 lyxrc.print_spool_command + ' ';
1140                                         if (target_name != "default") {
1141                                                 command2 += lyxrc.print_spool_printerprefix
1142                                                         + target_name
1143                                                         + ' ';
1144                                         }
1145                                         command2 += quoteName(psname);
1146                                         // First run dvips.
1147                                         // If successful, then spool command
1148                                         res = one.startscript(
1149                                                 Systemcall::Wait,
1150                                                 command);
1151
1152                                         if (res == 0)
1153                                                 res = one.startscript(
1154                                                         Systemcall::DontWait,
1155                                                         command2);
1156                                 } else {
1157                                         // case 2: print directly to a printer
1158                                         if (target_name != "default")
1159                                                 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
1160                                         res = one.startscript(
1161                                                 Systemcall::DontWait,
1162                                                 command + quoteName(dviname));
1163                                 }
1164
1165                         } else {
1166                                 // case 1: print to a file
1167                                 FileName const filename(makeAbsPath(target_name,
1168                                                         lyx_view_->buffer()->filePath()));
1169                                 FileName const dvifile(makeAbsPath(dviname, path));
1170                                 if (filename.exists()) {
1171                                         docstring text = bformat(
1172                                                 _("The file %1$s already exists.\n\n"
1173                                                   "Do you want to overwrite that file?"),
1174                                                 makeDisplayPath(filename.absFilename()));
1175                                         if (Alert::prompt(_("Overwrite file?"),
1176                                             text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
1177                                                 break;
1178                                 }
1179                                 command += ' ' + lyxrc.print_to_file
1180                                         + quoteName(filename.toFilesystemEncoding())
1181                                         + ' '
1182                                         + quoteName(dvifile.toFilesystemEncoding());
1183                                 res = one.startscript(Systemcall::DontWait,
1184                                                       command);
1185                         }
1186
1187                         if (res != 0)
1188                                 showPrintError(buffer->absFileName());
1189                         break;
1190                 }
1191
1192                 case LFUN_BUFFER_IMPORT:
1193                         doImport(argument);
1194                         break;
1195
1196                 case LFUN_BUFFER_AUTO_SAVE:
1197                         lyx_view_->buffer()->autoSave();
1198                         break;
1199
1200                 case LFUN_RECONFIGURE:
1201                         BOOST_ASSERT(lyx_view_);
1202                         // argument is any additional parameter to the configure.py command
1203                         reconfigure(*lyx_view_, argument);
1204                         break;
1205
1206                 case LFUN_HELP_OPEN: {
1207                         BOOST_ASSERT(lyx_view_);
1208                         string const arg = argument;
1209                         if (arg.empty()) {
1210                                 setErrorMessage(from_ascii(N_("Missing argument")));
1211                                 break;
1212                         }
1213                         FileName const fname = i18nLibFileSearch("doc", arg, "lyx");
1214                         if (fname.empty()) {
1215                                 lyxerr << "LyX: unable to find documentation file `"
1216                                                          << arg << "'. Bad installation?" << endl;
1217                                 break;
1218                         }
1219                         lyx_view_->message(bformat(_("Opening help file %1$s..."),
1220                                 makeDisplayPath(fname.absFilename())));
1221                         Buffer * buf = loadAndViewFile(fname, false);
1222                         if (buf) {
1223                                 updateLabels(*buf);
1224                                 lyx_view_->setBuffer(buf);
1225                                 buf->errors("Parse");
1226                         }
1227                         updateFlags = Update::None;
1228                         break;
1229                 }
1230
1231                 // --- version control -------------------------------
1232                 case LFUN_VC_REGISTER:
1233                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1234                         if (!ensureBufferClean(view()))
1235                                 break;
1236                         if (!lyx_view_->buffer()->lyxvc().inUse()) {
1237                                 lyx_view_->buffer()->lyxvc().registrer();
1238                                 reloadBuffer();
1239                         }
1240                         updateFlags = Update::Force;
1241                         break;
1242
1243                 case LFUN_VC_CHECK_IN:
1244                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1245                         if (!ensureBufferClean(view()))
1246                                 break;
1247                         if (lyx_view_->buffer()->lyxvc().inUse()
1248                                         && !lyx_view_->buffer()->isReadonly()) {
1249                                 lyx_view_->buffer()->lyxvc().checkIn();
1250                                 reloadBuffer();
1251                         }
1252                         break;
1253
1254                 case LFUN_VC_CHECK_OUT:
1255                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1256                         if (!ensureBufferClean(view()))
1257                                 break;
1258                         if (lyx_view_->buffer()->lyxvc().inUse()
1259                                         && lyx_view_->buffer()->isReadonly()) {
1260                                 lyx_view_->buffer()->lyxvc().checkOut();
1261                                 reloadBuffer();
1262                         }
1263                         break;
1264
1265                 case LFUN_VC_REVERT:
1266                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1267                         lyx_view_->buffer()->lyxvc().revert();
1268                         reloadBuffer();
1269                         break;
1270
1271                 case LFUN_VC_UNDO_LAST:
1272                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1273                         lyx_view_->buffer()->lyxvc().undoLast();
1274                         reloadBuffer();
1275                         break;
1276
1277                 // --- buffers ----------------------------------------
1278
1279                 case LFUN_FILE_NEW: {
1280                         BOOST_ASSERT(lyx_view_);
1281                         string name;
1282                         string tmpname = split(argument, name, ':'); // Split filename
1283                         Buffer * const b = newFile(name, tmpname);
1284                         if (b)
1285                                 lyx_view_->setBuffer(b);
1286                         updateFlags = Update::None;
1287                         break;
1288                 }
1289
1290                 case LFUN_FILE_OPEN:
1291                         BOOST_ASSERT(lyx_view_);
1292                         open(argument);
1293                         updateFlags = Update::None;
1294                         break;
1295
1296                 // --- lyxserver commands ----------------------------
1297                 case LFUN_SERVER_GET_NAME:
1298                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1299                         setMessage(from_utf8(lyx_view_->buffer()->absFileName()));
1300                         LYXERR(Debug::INFO, "FNAME["
1301                                 << lyx_view_->buffer()->absFileName() << ']');
1302                         break;
1303
1304                 case LFUN_SERVER_NOTIFY:
1305                         dispatch_buffer = keyseq.print(KeySequence::Portable);
1306                         theServer().notifyClient(to_utf8(dispatch_buffer));
1307                         break;
1308
1309                 case LFUN_SERVER_GOTO_FILE_ROW: {
1310                         BOOST_ASSERT(lyx_view_);
1311                         string file_name;
1312                         int row;
1313                         istringstream is(argument);
1314                         is >> file_name >> row;
1315                         Buffer * buf = 0;
1316                         bool loaded = false;
1317                         if (prefixIs(file_name, package().temp_dir().absFilename()))
1318                                 // Needed by inverse dvi search. If it is a file
1319                                 // in tmpdir, call the apropriated function
1320                                 buf = theBufferList().getBufferFromTmp(file_name);
1321                         else {
1322                                 // Must replace extension of the file to be .lyx
1323                                 // and get full path
1324                                 FileName const s = fileSearch(string(), changeExtension(file_name, ".lyx"), "lyx");
1325                                 // Either change buffer or load the file
1326                                 if (theBufferList().exists(s.absFilename()))
1327                                         buf = theBufferList().getBuffer(s.absFilename());
1328                                 else {
1329                                         buf = loadAndViewFile(s);
1330                                         loaded = true;
1331                                 }
1332                         }
1333
1334                         if (!buf) {
1335                                 updateFlags = Update::None;
1336                                 break;
1337                         }
1338
1339                         updateLabels(*buf);
1340                         lyx_view_->setBuffer(buf);
1341                         view()->setCursorFromRow(row);
1342                         if (loaded)
1343                                 buf->errors("Parse");
1344                         updateFlags = Update::FitCursor;
1345                         break;
1346                 }
1347
1348
1349                 case LFUN_DIALOG_SHOW_NEW_INSET: {
1350                         BOOST_ASSERT(lyx_view_);
1351                         string const name = cmd.getArg(0);
1352                         InsetCode code = insetCode(name);
1353                         string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1354                         bool insetCodeOK = true;
1355                         switch (code) {
1356                         case BIBITEM_CODE:
1357                         case BIBTEX_CODE:
1358                         case INDEX_CODE:
1359                         case LABEL_CODE:
1360                         case NOMENCL_CODE:
1361                         case REF_CODE:
1362                         case TOC_CODE:
1363                         case HYPERLINK_CODE: {
1364                                 InsetCommandParams p(code);
1365                                 data = InsetCommandMailer::params2string(name, p);
1366                                 break;
1367                         } 
1368                         case INCLUDE_CODE: {
1369                                 // data is the include type: one of "include",
1370                                 // "input", "verbatiminput" or "verbatiminput*"
1371                                 if (data.empty())
1372                                         // default type is requested
1373                                         data = "include";
1374                                 InsetCommandParams p(INCLUDE_CODE, data);
1375                                 data = InsetCommandMailer::params2string("include", p);
1376                                 break;
1377                         } 
1378                         case BOX_CODE: {
1379                                 // \c data == "Boxed" || "Frameless" etc
1380                                 InsetBoxParams p(data);
1381                                 data = InsetBoxMailer::params2string(p);
1382                                 break;
1383                         } 
1384                         case BRANCH_CODE: {
1385                                 InsetBranchParams p;
1386                                 data = InsetBranchMailer::params2string(p);
1387                                 break;
1388                         } 
1389                         case CITE_CODE: {
1390                                 InsetCommandParams p(CITE_CODE);
1391                                 data = InsetCommandMailer::params2string(name, p);
1392                                 break;
1393                         } 
1394                         case ERT_CODE: {
1395                                 data = InsetERTMailer::params2string(InsetCollapsable::Open);
1396                                 break;
1397                         } 
1398                         case EXTERNAL_CODE: {
1399                                 InsetExternalParams p;
1400                                 Buffer const & buffer = *lyx_view_->buffer();
1401                                 data = InsetExternalMailer::params2string(p, buffer);
1402                                 break;
1403                         } 
1404                         case FLOAT_CODE:  {
1405                                 InsetFloatParams p;
1406                                 data = InsetFloatMailer::params2string(p);
1407                                 break;
1408                         } 
1409                         case LISTINGS_CODE: {
1410                                 InsetListingsParams p;
1411                                 data = InsetListingsMailer::params2string(p);
1412                                 break;
1413                         } 
1414                         case GRAPHICS_CODE: {
1415                                 InsetGraphicsParams p;
1416                                 Buffer const & buffer = *lyx_view_->buffer();
1417                                 data = InsetGraphicsMailer::params2string(p, buffer);
1418                                 break;
1419                         } 
1420                         case NOTE_CODE: {
1421                                 InsetNoteParams p;
1422                                 data = InsetNoteMailer::params2string(p);
1423                                 break;
1424                         } 
1425                         case VSPACE_CODE: {
1426                                 VSpace space;
1427                                 data = InsetVSpaceMailer::params2string(space);
1428                                 break;
1429                         } 
1430                         case WRAP_CODE: {
1431                                 InsetWrapParams p;
1432                                 data = InsetWrapMailer::params2string(p);
1433                                 break;
1434                         }
1435                         default:
1436                                 lyxerr << "Inset type '" << name << 
1437                                         "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << std:: endl;
1438                                 insetCodeOK = false;
1439                                 break;
1440                         } // end switch(code)
1441                         if (insetCodeOK)
1442                                 dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1443                         break;
1444                 }
1445
1446                 case LFUN_CITATION_INSERT: {
1447                         BOOST_ASSERT(lyx_view_);
1448                         if (!argument.empty()) {
1449                                 // we can have one optional argument, delimited by '|'
1450                                 // citation-insert <key>|<text_before>
1451                                 // this should be enhanced to also support text_after
1452                                 // and citation style
1453                                 string arg = argument;
1454                                 string opt1;
1455                                 if (contains(argument, "|")) {
1456                                         arg = token(argument, '|', 0);
1457                                         opt1 = token(argument, '|', 1);
1458                                 }
1459                                 InsetCommandParams icp(CITE_CODE);
1460                                 icp["key"] = from_utf8(arg);
1461                                 if (!opt1.empty())
1462                                         icp["before"] = from_utf8(opt1);
1463                                 string icstr = InsetCommandMailer::params2string("citation", icp);
1464                                 FuncRequest fr(LFUN_INSET_INSERT, icstr);
1465                                 dispatch(fr);
1466                         } else
1467                                 dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1468                         break;
1469                 }
1470
1471                 case LFUN_BUFFER_CHILD_OPEN: {
1472                         BOOST_ASSERT(lyx_view_ && lyx_view_->buffer());
1473                         Buffer * parent = lyx_view_->buffer();
1474                         FileName filename = makeAbsPath(argument, parent->filePath());
1475                         view()->saveBookmark(false);
1476                         Buffer * child = 0;
1477                         bool parsed = false;
1478                         if (theBufferList().exists(filename.absFilename())) {
1479                                 child = theBufferList().getBuffer(filename.absFilename());
1480                         } else {
1481                                 setMessage(bformat(_("Opening child document %1$s..."),
1482                                         makeDisplayPath(filename.absFilename())));
1483                                 child = loadAndViewFile(filename, true);
1484                                 parsed = true;
1485                         }
1486                         if (child) {
1487                                 // Set the parent name of the child document.
1488                                 // This makes insertion of citations and references in the child work,
1489                                 // when the target is in the parent or another child document.
1490                                 child->setParentName(parent->absFileName());
1491                                 updateLabels(*child->masterBuffer());
1492                                 lyx_view_->setBuffer(child);
1493                                 if (parsed)
1494                                         child->errors("Parse");
1495                         }
1496
1497                         // If a screen update is required (in case where auto_open is false), 
1498                         // setBuffer() would have taken care of it already. Otherwise we shall 
1499                         // reset the update flag because it can cause a circular problem.
1500                         // See bug 3970.
1501                         updateFlags = Update::None;
1502                         break;
1503                 }
1504
1505                 case LFUN_TOGGLE_CURSOR_FOLLOWS_SCROLLBAR:
1506                         BOOST_ASSERT(lyx_view_);
1507                         lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1508                         break;
1509
1510                 case LFUN_KEYMAP_OFF:
1511                         BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1512                         lyx_view_->view()->getIntl().keyMapOn(false);
1513                         break;
1514
1515                 case LFUN_KEYMAP_PRIMARY:
1516                         BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1517                         lyx_view_->view()->getIntl().keyMapPrim();
1518                         break;
1519
1520                 case LFUN_KEYMAP_SECONDARY:
1521                         BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1522                         lyx_view_->view()->getIntl().keyMapSec();
1523                         break;
1524
1525                 case LFUN_KEYMAP_TOGGLE:
1526                         BOOST_ASSERT(lyx_view_ && lyx_view_->view());
1527                         lyx_view_->view()->getIntl().toggleKeyMap();
1528                         break;
1529
1530                 case LFUN_REPEAT: {
1531                         // repeat command
1532                         string countstr;
1533                         string rest = split(argument, countstr, ' ');
1534                         istringstream is(countstr);
1535                         int count = 0;
1536                         is >> count;
1537                         lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1538                         for (int i = 0; i < count; ++i)
1539                                 dispatch(lyxaction.lookupFunc(rest));
1540                         break;
1541                 }
1542
1543                 case LFUN_COMMAND_SEQUENCE: {
1544                         // argument contains ';'-terminated commands
1545                         string arg = argument;
1546                         while (!arg.empty()) {
1547                                 string first;
1548                                 arg = split(arg, first, ';');
1549                                 FuncRequest func(lyxaction.lookupFunc(first));
1550                                 func.origin = cmd.origin;
1551                                 dispatch(func);
1552                         }
1553                         break;
1554                 }
1555
1556                 case LFUN_CALL: {
1557                         FuncRequest func;
1558                         if (LyX::ref().topLevelCmdDef().lock(argument, func)) {
1559                                 func.origin = cmd.origin;
1560                                 dispatch(func);
1561                                 LyX::ref().topLevelCmdDef().release(argument);
1562                         } else {
1563                                 if (func.action == LFUN_UNKNOWN_ACTION) {
1564                                         // unknown command definition
1565                                         lyxerr << "Warning: unknown command definition `"
1566                                                    << argument << "'"
1567                                                    << endl;
1568                                 } else {
1569                                         // recursion detected
1570                                         lyxerr << "Warning: Recursion in the command definition `"
1571                                                    << argument << "' detected"
1572                                                    << endl;
1573                                 }
1574                         }
1575                         break;
1576                 }
1577
1578                 case LFUN_PREFERENCES_SAVE: {
1579                         lyxrc.write(makeAbsPath("preferences",
1580                                                 package().user_support().absFilename()),
1581                                     false);
1582                         break;
1583                 }
1584
1585                 case LFUN_SET_COLOR: {
1586                         string lyx_name;
1587                         string const x11_name = split(argument, lyx_name, ' ');
1588                         if (lyx_name.empty() || x11_name.empty()) {
1589                                 setErrorMessage(from_ascii(N_(
1590                                                 "Syntax: set-color <lyx_name>"
1591                                                 " <x11_name>")));
1592                                 break;
1593                         }
1594
1595                         bool const graphicsbg_changed =
1596                                 (lyx_name == lcolor.getLyXName(Color_graphicsbg) &&
1597                                  x11_name != lcolor.getX11Name(Color_graphicsbg));
1598
1599                         if (!lcolor.setColor(lyx_name, x11_name)) {
1600                                 setErrorMessage(
1601                                                 bformat(_("Set-color \"%1$s\" failed "
1602                                                                        "- color is undefined or "
1603                                                                        "may not be redefined"),
1604                                                                            from_utf8(lyx_name)));
1605                                 break;
1606                         }
1607
1608                         theApp()->updateColor(lcolor.getFromLyXName(lyx_name));
1609
1610                         if (graphicsbg_changed) {
1611                                 // FIXME: The graphics cache no longer has a changeDisplay method.
1612 #if 0
1613                                 graphics::GCache::get().changeDisplay(true);
1614 #endif
1615                         }
1616                         break;
1617                 }
1618
1619                 case LFUN_MESSAGE:
1620                         BOOST_ASSERT(lyx_view_);
1621                         lyx_view_->message(from_utf8(argument));
1622                         break;
1623
1624                 case LFUN_EXTERNAL_EDIT: {
1625                         BOOST_ASSERT(lyx_view_);
1626                         FuncRequest fr(action, argument);
1627                         InsetExternal().dispatch(view()->cursor(), fr);
1628                         break;
1629                 }
1630
1631                 case LFUN_GRAPHICS_EDIT: {
1632                         FuncRequest fr(action, argument);
1633                         InsetGraphics().dispatch(view()->cursor(), fr);
1634                         break;
1635                 }
1636
1637                 case LFUN_ALL_INSETS_TOGGLE: {
1638                         BOOST_ASSERT(lyx_view_);
1639                         string action;
1640                         string const name = split(argument, action, ' ');
1641                         InsetCode const inset_code = insetCode(name);
1642
1643                         Cursor & cur = view()->cursor();
1644                         FuncRequest fr(LFUN_INSET_TOGGLE, action);
1645
1646                         Inset & inset = lyx_view_->buffer()->inset();
1647                         InsetIterator it  = inset_iterator_begin(inset);
1648                         InsetIterator const end = inset_iterator_end(inset);
1649                         for (; it != end; ++it) {
1650                                 if (!it->asInsetMath()
1651                                     && (inset_code == NO_CODE
1652                                     || inset_code == it->lyxCode())) {
1653                                         Cursor tmpcur = cur;
1654                                         tmpcur.pushBackward(*it);
1655                                         it->dispatch(tmpcur, fr);
1656                                 }
1657                         }
1658                         updateFlags = Update::Force | Update::FitCursor;
1659                         break;
1660                 }
1661
1662                 case LFUN_BUFFER_LANGUAGE: {
1663                         BOOST_ASSERT(lyx_view_);
1664                         Buffer & buffer = *lyx_view_->buffer();
1665                         Language const * oldL = buffer.params().language;
1666                         Language const * newL = languages.getLanguage(argument);
1667                         if (!newL || oldL == newL)
1668                                 break;
1669
1670                         if (oldL->rightToLeft() == newL->rightToLeft()
1671                             && !buffer.isMultiLingual())
1672                                 buffer.changeLanguage(oldL, newL);
1673                         break;
1674                 }
1675
1676                 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1677                         string const fname =
1678                                 addName(addPath(package().user_support().absFilename(), "templates/"),
1679                                         "defaults.lyx");
1680                         Buffer defaults(fname);
1681
1682                         istringstream ss(argument);
1683                         Lexer lex(0,0);
1684                         lex.setStream(ss);
1685                         int const unknown_tokens = defaults.readHeader(lex);
1686
1687                         if (unknown_tokens != 0) {
1688                                 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1689                                        << unknown_tokens << " unknown token"
1690                                        << (unknown_tokens == 1 ? "" : "s")
1691                                        << endl;
1692                         }
1693
1694                         if (defaults.writeFile(FileName(defaults.absFileName())))
1695                                 setMessage(bformat(_("Document defaults saved in %1$s"),
1696                                                    makeDisplayPath(fname)));
1697                         else
1698                                 setErrorMessage(from_ascii(N_("Unable to save document defaults")));
1699                         break;
1700                 }
1701
1702                 case LFUN_BUFFER_PARAMS_APPLY: {
1703                         BOOST_ASSERT(lyx_view_);
1704                         biblio::CiteEngine const oldEngine =
1705                                         lyx_view_->buffer()->params().getEngine();
1706                         
1707                         Buffer * buffer = lyx_view_->buffer();
1708
1709                         TextClassPtr oldClass = buffer->params().getTextClassPtr();
1710
1711                         Cursor & cur = view()->cursor();
1712                         cur.recordUndoFullDocument();
1713                         
1714                         istringstream ss(argument);
1715                         Lexer lex(0,0);
1716                         lex.setStream(ss);
1717                         int const unknown_tokens = buffer->readHeader(lex);
1718
1719                         if (unknown_tokens != 0) {
1720                                 lyxerr << "Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1721                                                 << unknown_tokens << " unknown token"
1722                                                 << (unknown_tokens == 1 ? "" : "s")
1723                                                 << endl;
1724                         }
1725                         
1726                         updateLayout(oldClass, buffer);
1727                         
1728                         biblio::CiteEngine const newEngine =
1729                                         lyx_view_->buffer()->params().getEngine();
1730                         
1731                         if (oldEngine != newEngine) {
1732                                 FuncRequest fr(LFUN_INSET_REFRESH);
1733         
1734                                 Inset & inset = lyx_view_->buffer()->inset();
1735                                 InsetIterator it  = inset_iterator_begin(inset);
1736                                 InsetIterator const end = inset_iterator_end(inset);
1737                                 for (; it != end; ++it)
1738                                         if (it->lyxCode() == CITE_CODE)
1739                                                 it->dispatch(cur, fr);
1740                         }
1741                         
1742                         updateFlags = Update::Force | Update::FitCursor;
1743                         break;
1744                 }
1745                 
1746                 case LFUN_LAYOUT_MODULES_CLEAR: {
1747                         BOOST_ASSERT(lyx_view_);
1748                         Buffer * buffer = lyx_view_->buffer();
1749                         TextClassPtr oldClass = buffer->params().getTextClassPtr();
1750                         view()->cursor().recordUndoFullDocument();
1751                         buffer->params().clearLayoutModules();
1752                         updateLayout(oldClass, buffer);
1753                         updateFlags = Update::Force | Update::FitCursor;
1754                         break;
1755                 }
1756                 
1757                 case LFUN_LAYOUT_MODULE_ADD: {
1758                         BOOST_ASSERT(lyx_view_);
1759                         Buffer * buffer = lyx_view_->buffer();
1760                         TextClassPtr oldClass = buffer->params().getTextClassPtr();
1761                         view()->cursor().recordUndoFullDocument();
1762                         buffer->params().addLayoutModule(argument);
1763                         updateLayout(oldClass, buffer);
1764                         updateFlags = Update::Force | Update::FitCursor;
1765                         break;
1766                 }
1767
1768                 case LFUN_TEXTCLASS_APPLY: {
1769                         BOOST_ASSERT(lyx_view_);
1770                         Buffer * buffer = lyx_view_->buffer();
1771
1772                         loadTextClass(argument);
1773
1774                         std::pair<bool, textclass_type> const tc_pair =
1775                                 textclasslist.numberOfClass(argument);
1776
1777                         if (!tc_pair.first)
1778                                 break;
1779
1780                         textclass_type const old_class = buffer->params().getBaseClass();
1781                         textclass_type const new_class = tc_pair.second;
1782
1783                         if (old_class == new_class)
1784                                 // nothing to do
1785                                 break;
1786
1787                         //Save the old, possibly modular, layout for use in conversion.
1788                         TextClassPtr oldClass = buffer->params().getTextClassPtr();
1789                         view()->cursor().recordUndoFullDocument();
1790                         buffer->params().setBaseClass(new_class);
1791                         updateLayout(oldClass, buffer);
1792                         updateFlags = Update::Force | Update::FitCursor;
1793                         break;
1794                 }
1795                 
1796                 case LFUN_LAYOUT_RELOAD: {
1797                         BOOST_ASSERT(lyx_view_);
1798                         Buffer * buffer = lyx_view_->buffer();
1799                         TextClassPtr oldClass = buffer->params().getTextClassPtr();
1800                         textclass_type const tc = buffer->params().getBaseClass();
1801                         textclasslist.reset(tc);
1802                         buffer->params().setBaseClass(tc);
1803                         updateLayout(oldClass, buffer);
1804                         updateFlags = Update::Force | Update::FitCursor;
1805                         break;
1806                 }
1807
1808                 case LFUN_TEXTCLASS_LOAD:
1809                         loadTextClass(argument);
1810                         break;
1811
1812                 case LFUN_LYXRC_APPLY: {
1813                         LyXRC const lyxrc_orig = lyxrc;
1814
1815                         istringstream ss(argument);
1816                         bool const success = lyxrc.read(ss) == 0;
1817
1818                         if (!success) {
1819                                 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1820                                        << "Unable to read lyxrc data"
1821                                        << endl;
1822                                 break;
1823                         }
1824
1825                         actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1826
1827                         theApp()->resetGui();
1828
1829                         /// We force the redraw in any case because there might be
1830                         /// some screen font changes.
1831                         /// FIXME: only the current view will be updated. the Gui
1832                         /// class is able to furnish the list of views.
1833                         updateFlags = Update::Force;
1834                         break;
1835                 }
1836
1837                 case LFUN_BOOKMARK_GOTO:
1838                         // go to bookmark, open unopened file and switch to buffer if necessary
1839                         gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1840                         break;
1841
1842                 case LFUN_BOOKMARK_CLEAR:
1843                         LyX::ref().session().bookmarks().clear();
1844                         break;
1845
1846                 default: {
1847                         BOOST_ASSERT(lyx_view_);
1848                         view()->cursor().dispatch(cmd);
1849                         updateFlags = view()->cursor().result().update();
1850                         if (!view()->cursor().result().dispatched())
1851                                 updateFlags = view()->dispatch(cmd);
1852                         break;
1853                 }
1854                 }
1855
1856                 if (lyx_view_ && lyx_view_->buffer()) {
1857                         // BufferView::update() updates the ViewMetricsInfo and
1858                         // also initializes the position cache for all insets in
1859                         // (at least partially) visible top-level paragraphs.
1860                         // We will redraw the screen only if needed.
1861                         view()->processUpdateFlags(updateFlags);
1862
1863                         // if we executed a mutating lfun, mark the buffer as dirty
1864                         if (flag.enabled()
1865                             && !lyxaction.funcHasFlag(action, LyXAction::NoBuffer)
1866                             && !lyxaction.funcHasFlag(action, LyXAction::ReadOnly))
1867                                 lyx_view_->buffer()->markDirty();
1868
1869                         //Do we have a selection?
1870                         theSelection().haveSelection(view()->cursor().selection());
1871
1872                         if (view()->cursor().inTexted()) {
1873                         }
1874                 }
1875         }
1876         if (!quitting && lyx_view_) {
1877                 // Some messages may already be translated, so we cannot use _()
1878                 sendDispatchMessage(translateIfPossible(getMessage()), cmd);
1879         }
1880 }
1881
1882
1883 void LyXFunc::sendDispatchMessage(docstring const & msg, FuncRequest const & cmd)
1884 {
1885         const bool verbose = (cmd.origin == FuncRequest::MENU
1886                               || cmd.origin == FuncRequest::TOOLBAR
1887                               || cmd.origin == FuncRequest::COMMANDBUFFER);
1888
1889         if (cmd.action == LFUN_SELF_INSERT || !verbose) {
1890                 LYXERR(Debug::ACTION, "dispatch msg is " << to_utf8(msg));
1891                 if (!msg.empty())
1892                         lyx_view_->message(msg);
1893                 return;
1894         }
1895
1896         docstring dispatch_msg = msg;
1897         if (!dispatch_msg.empty())
1898                 dispatch_msg += ' ';
1899
1900         docstring comname = from_utf8(lyxaction.getActionName(cmd.action));
1901
1902         bool argsadded = false;
1903
1904         if (!cmd.argument().empty()) {
1905                 if (cmd.action != LFUN_UNKNOWN_ACTION) {
1906                         comname += ' ' + cmd.argument();
1907                         argsadded = true;
1908                 }
1909         }
1910
1911         docstring const shortcuts = theTopLevelKeymap().printBindings(cmd);
1912
1913         if (!shortcuts.empty())
1914                 comname += ": " + shortcuts;
1915         else if (!argsadded && !cmd.argument().empty())
1916                 comname += ' ' + cmd.argument();
1917
1918         if (!comname.empty()) {
1919                 comname = rtrim(comname);
1920                 dispatch_msg += '(' + rtrim(comname) + ')';
1921         }
1922
1923         LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1924         if (!dispatch_msg.empty())
1925                 lyx_view_->message(dispatch_msg);
1926 }
1927
1928
1929 void LyXFunc::menuNew(string const & name, bool fromTemplate)
1930 {
1931         // FIXME: initpath is not used. What to do?
1932         string initpath = lyxrc.document_path;
1933         string filename(name);
1934
1935         if (lyx_view_->buffer()) {
1936                 string const trypath = lyx_view_->buffer()->filePath();
1937                 // If directory is writeable, use this as default.
1938                 if (FileName(trypath).isDirWritable())
1939                         initpath = trypath;
1940         }
1941
1942         static int newfile_number;
1943
1944         if (filename.empty()) {
1945                 filename = addName(lyxrc.document_path,
1946                             "newfile" + convert<string>(++newfile_number) + ".lyx");
1947                 while (theBufferList().exists(filename) ||
1948                        FileName(filename).isReadableFile()) {
1949                         ++newfile_number;
1950                         filename = addName(lyxrc.document_path,
1951                                            "newfile" +  convert<string>(newfile_number) +
1952                                     ".lyx");
1953                 }
1954         }
1955
1956         // The template stuff
1957         string templname;
1958         if (fromTemplate) {
1959                 FileDialog dlg(_("Select template file"));
1960                 dlg.setButton1(_("Documents|#o#O"), from_utf8(lyxrc.document_path));
1961                 dlg.setButton1(_("Templates|#T#t"), from_utf8(lyxrc.template_path));
1962
1963                 FileDialog::Result result =
1964                         dlg.open(from_utf8(lyxrc.template_path),
1965                                      FileFilterList(_("LyX Documents (*.lyx)")),
1966                                      docstring());
1967
1968                 if (result.first == FileDialog::Later)
1969                         return;
1970                 if (result.second.empty())
1971                         return;
1972                 templname = to_utf8(result.second);
1973         }
1974
1975         Buffer * const b = newFile(filename, templname, !name.empty());
1976         if (b)
1977                 lyx_view_->setBuffer(b);
1978 }
1979
1980
1981 Buffer * LyXFunc::loadAndViewFile(FileName const & filename, bool tolastfiles)
1982 {
1983         lyx_view_->setBusy(true);
1984
1985         Buffer * newBuffer = checkAndLoadLyXFile(filename);
1986
1987         if (!newBuffer) {
1988                 lyx_view_->message(_("Document not loaded."));
1989                 lyx_view_->setBusy(false);
1990                 return 0;
1991         }
1992
1993         lyx_view_->setBuffer(newBuffer);
1994
1995         // scroll to the position when the file was last closed
1996         if (lyxrc.use_lastfilepos) {
1997                 LastFilePosSection::FilePos filepos =
1998                         LyX::ref().session().lastFilePos().load(filename);
1999                 lyx_view_->view()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
2000         }
2001
2002         if (tolastfiles)
2003                 LyX::ref().session().lastFiles().add(filename);
2004
2005         lyx_view_->setBusy(false);
2006         return newBuffer;
2007 }
2008
2009
2010 void LyXFunc::open(string const & fname)
2011 {
2012         string initpath = lyxrc.document_path;
2013
2014         if (lyx_view_->buffer()) {
2015                 string const trypath = lyx_view_->buffer()->filePath();
2016                 // If directory is writeable, use this as default.
2017                 if (FileName(trypath).isDirWritable())
2018                         initpath = trypath;
2019         }
2020
2021         string filename;
2022
2023         if (fname.empty()) {
2024                 FileDialog dlg(_("Select document to open"), LFUN_FILE_OPEN);
2025                 dlg.setButton1(_("Documents|#o#O"), from_utf8(lyxrc.document_path));
2026                 dlg.setButton2(_("Examples|#E#e"),
2027                                 from_utf8(addPath(package().system_support().absFilename(), "examples")));
2028
2029                 FileDialog::Result result =
2030                         dlg.open(from_utf8(initpath),
2031                                      FileFilterList(_("LyX Documents (*.lyx)")),
2032                                      docstring());
2033
2034                 if (result.first == FileDialog::Later)
2035                         return;
2036
2037                 filename = to_utf8(result.second);
2038
2039                 // check selected filename
2040                 if (filename.empty()) {
2041                         lyx_view_->message(_("Canceled."));
2042                         return;
2043                 }
2044         } else
2045                 filename = fname;
2046
2047         // get absolute path of file and add ".lyx" to the filename if
2048         // necessary
2049         FileName const fullname = fileSearch(string(), filename, "lyx");
2050         if (!fullname.empty())
2051                 filename = fullname.absFilename();
2052
2053         // if the file doesn't exist, let the user create one
2054         if (!fullname.exists()) {
2055                 // the user specifically chose this name. Believe him.
2056                 Buffer * const b = newFile(filename, string(), true);
2057                 if (b)
2058                         lyx_view_->setBuffer(b);
2059                 return;
2060         }
2061
2062         docstring const disp_fn = makeDisplayPath(filename);
2063         lyx_view_->message(bformat(_("Opening document %1$s..."), disp_fn));
2064
2065         docstring str2;
2066         Buffer * buf = loadAndViewFile(fullname);
2067         if (buf) {
2068                 updateLabels(*buf);
2069                 lyx_view_->setBuffer(buf);
2070                 buf->errors("Parse");
2071                 str2 = bformat(_("Document %1$s opened."), disp_fn);
2072         } else {
2073                 str2 = bformat(_("Could not open document %1$s"), disp_fn);
2074         }
2075         lyx_view_->message(str2);
2076 }
2077
2078
2079 void LyXFunc::doImport(string const & argument)
2080 {
2081         string format;
2082         string filename = split(argument, format, ' ');
2083
2084         LYXERR(Debug::INFO, "LyXFunc::doImport: " << format
2085                             << " file: " << filename);
2086
2087         // need user interaction
2088         if (filename.empty()) {
2089                 string initpath = lyxrc.document_path;
2090
2091                 if (lyx_view_->buffer()) {
2092                         string const trypath = lyx_view_->buffer()->filePath();
2093                         // If directory is writeable, use this as default.
2094                         if (FileName(trypath).isDirWritable())
2095                                 initpath = trypath;
2096                 }
2097
2098                 docstring const text = bformat(_("Select %1$s file to import"),
2099                         formats.prettyName(format));
2100
2101                 FileDialog dlg(text, LFUN_BUFFER_IMPORT);
2102                 dlg.setButton1(_("Documents|#o#O"), from_utf8(lyxrc.document_path));
2103                 dlg.setButton2(_("Examples|#E#e"),
2104                         from_utf8(addPath(package().system_support().absFilename(), "examples")));
2105
2106                 docstring filter = formats.prettyName(format);
2107                 filter += " (*.";
2108                 // FIXME UNICODE
2109                 filter += from_utf8(formats.extension(format));
2110                 filter += ')';
2111
2112                 FileDialog::Result result =
2113                         dlg.open(from_utf8(initpath),
2114                                      FileFilterList(filter),
2115                                      docstring());
2116
2117                 if (result.first == FileDialog::Later)
2118                         return;
2119
2120                 filename = to_utf8(result.second);
2121
2122                 // check selected filename
2123                 if (filename.empty())
2124                         lyx_view_->message(_("Canceled."));
2125         }
2126
2127         if (filename.empty())
2128                 return;
2129
2130         // get absolute path of file
2131         FileName const fullname(makeAbsPath(filename));
2132
2133         FileName const lyxfile(changeExtension(fullname.absFilename(), ".lyx"));
2134
2135         // Check if the document already is open
2136         if (use_gui && theBufferList().exists(lyxfile.absFilename())) {
2137                 if (!theBufferList().close(theBufferList().getBuffer(lyxfile.absFilename()), true)) {
2138                         lyx_view_->message(_("Canceled."));
2139                         return;
2140                 }
2141         }
2142
2143         // if the file exists already, and we didn't do
2144         // -i lyx thefile.lyx, warn
2145         if (lyxfile.exists() && fullname != lyxfile) {
2146                 docstring const file = makeDisplayPath(lyxfile.absFilename(), 30);
2147
2148                 docstring text = bformat(_("The document %1$s already exists.\n\n"
2149                                                      "Do you want to overwrite that document?"), file);
2150                 int const ret = Alert::prompt(_("Overwrite document?"),
2151                         text, 0, 1, _("&Overwrite"), _("&Cancel"));
2152
2153                 if (ret == 1) {
2154                         lyx_view_->message(_("Canceled."));
2155                         return;
2156                 }
2157         }
2158
2159         ErrorList errorList;
2160         import(lyx_view_, fullname, format, errorList);
2161         // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2162 }
2163
2164
2165 void LyXFunc::closeBuffer()
2166 {
2167         // goto bookmark to update bookmark pit.
2168         for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i)
2169                 gotoBookmark(i+1, false, false);
2170         
2171         theBufferList().close(lyx_view_->buffer(), true);
2172 }
2173
2174
2175 void LyXFunc::reloadBuffer()
2176 {
2177         FileName filename(lyx_view_->buffer()->absFileName());
2178         docstring const disp_fn = makeDisplayPath(filename.absFilename());
2179         docstring str;
2180         closeBuffer();
2181         Buffer * buf = loadAndViewFile(filename);
2182         if (buf) {
2183                 updateLabels(*buf);
2184                 lyx_view_->setBuffer(buf);
2185                 buf->errors("Parse");
2186                 str = bformat(_("Document %1$s reloaded."), disp_fn);
2187         } else {
2188                 str = bformat(_("Could not reload document %1$s"), disp_fn);
2189         }
2190         lyx_view_->message(str);
2191 }
2192
2193 // Each "lyx_view_" should have it's own message method. lyxview and
2194 // the minibuffer would use the minibuffer, but lyxserver would
2195 // send an ERROR signal to its client.  Alejandro 970603
2196 // This function is bit problematic when it comes to NLS, to make the
2197 // lyx servers client be language indepenent we must not translate
2198 // strings sent to this func.
2199 void LyXFunc::setErrorMessage(docstring const & m) const
2200 {
2201         dispatch_buffer = m;
2202         errorstat = true;
2203 }
2204
2205
2206 void LyXFunc::setMessage(docstring const & m) const
2207 {
2208         dispatch_buffer = m;
2209 }
2210
2211
2212 docstring const LyXFunc::viewStatusMessage()
2213 {
2214         // When meta-fake key is pressed, show the key sequence so far + "M-".
2215         if (wasMetaKey())
2216                 return keyseq.print(KeySequence::ForGui) + "M-";
2217
2218         // Else, when a non-complete key sequence is pressed,
2219         // show the available options.
2220         if (keyseq.length() > 0 && !keyseq.deleted())
2221                 return keyseq.printOptions(true);
2222
2223         BOOST_ASSERT(lyx_view_);
2224         if (!lyx_view_->buffer())
2225                 return _("Welcome to LyX!");
2226
2227         return view()->cursor().currentState();
2228 }
2229
2230
2231 BufferView * LyXFunc::view() const
2232 {
2233         BOOST_ASSERT(lyx_view_);
2234         return lyx_view_->view();
2235 }
2236
2237
2238 bool LyXFunc::wasMetaKey() const
2239 {
2240         return (meta_fake_bit != NoModifier);
2241 }
2242
2243
2244 void LyXFunc::updateLayout(TextClassPtr const & oldlayout,
2245                            Buffer * buffer)
2246 {
2247         lyx_view_->message(_("Converting document to new document class..."));
2248         
2249         StableDocIterator backcur(view()->cursor());
2250         ErrorList & el = buffer->errorList("Class Switch");
2251         cap::switchBetweenClasses(
2252                         oldlayout, buffer->params().getTextClassPtr(),
2253                         static_cast<InsetText &>(buffer->inset()), el);
2254
2255         view()->setCursor(backcur.asDocIterator(&(buffer->inset())));
2256
2257         buffer->errors("Class Switch");
2258         updateLabels(*buffer);
2259 }
2260
2261
2262 namespace {
2263
2264 void actOnUpdatedPrefs(LyXRC const & lyxrc_orig, LyXRC const & lyxrc_new)
2265 {
2266         // Why the switch you might ask. It is a trick to ensure that all
2267         // the elements in the LyXRCTags enum is handled. As you can see
2268         // there are no breaks at all. So it is just a huge fall-through.
2269         // The nice thing is that we will get a warning from the compiler
2270         // if we forget an element.
2271         LyXRC::LyXRCTags tag = LyXRC::RC_LAST;
2272         switch (tag) {
2273         case LyXRC::RC_ACCEPT_COMPOUND:
2274         case LyXRC::RC_ALT_LANG:
2275         case LyXRC::RC_PLAINTEXT_ROFF_COMMAND:
2276         case LyXRC::RC_PLAINTEXT_LINELEN:
2277         case LyXRC::RC_AUTOREGIONDELETE:
2278         case LyXRC::RC_AUTORESET_OPTIONS:
2279         case LyXRC::RC_AUTOSAVE:
2280         case LyXRC::RC_AUTO_NUMBER:
2281         case LyXRC::RC_BACKUPDIR_PATH:
2282         case LyXRC::RC_BIBTEX_COMMAND:
2283         case LyXRC::RC_BINDFILE:
2284         case LyXRC::RC_CHECKLASTFILES:
2285         case LyXRC::RC_USELASTFILEPOS:
2286         case LyXRC::RC_LOADSESSION:
2287         case LyXRC::RC_CHKTEX_COMMAND:
2288         case LyXRC::RC_CONVERTER:
2289         case LyXRC::RC_CONVERTER_CACHE_MAXAGE:
2290         case LyXRC::RC_COPIER:
2291         case LyXRC::RC_CURSOR_FOLLOWS_SCROLLBAR:
2292         case LyXRC::RC_CUSTOM_EXPORT_COMMAND:
2293         case LyXRC::RC_CUSTOM_EXPORT_FORMAT:
2294         case LyXRC::RC_DATE_INSERT_FORMAT:
2295         case LyXRC::RC_DEFAULT_LANGUAGE:
2296         case LyXRC::RC_DEFAULT_PAPERSIZE:
2297         case LyXRC::RC_DEFFILE:
2298         case LyXRC::RC_DIALOGS_ICONIFY_WITH_MAIN:
2299         case LyXRC::RC_DISPLAY_GRAPHICS:
2300         case LyXRC::RC_DOCUMENTPATH:
2301                 if (lyxrc_orig.document_path != lyxrc_new.document_path) {
2302                         FileName path(lyxrc_new.document_path);
2303                         if (path.exists() && path.isDirectory())
2304                                 support::package().document_dir() = FileName(lyxrc.document_path);
2305                 }
2306         case LyXRC::RC_ESC_CHARS:
2307         case LyXRC::RC_FONT_ENCODING:
2308         case LyXRC::RC_FORMAT:
2309         case LyXRC::RC_INDEX_COMMAND:
2310         case LyXRC::RC_INPUT:
2311         case LyXRC::RC_KBMAP:
2312         case LyXRC::RC_KBMAP_PRIMARY:
2313         case LyXRC::RC_KBMAP_SECONDARY:
2314         case LyXRC::RC_LABEL_INIT_LENGTH:
2315         case LyXRC::RC_LANGUAGE_AUTO_BEGIN:
2316         case LyXRC::RC_LANGUAGE_AUTO_END:
2317         case LyXRC::RC_LANGUAGE_COMMAND_BEGIN:
2318         case LyXRC::RC_LANGUAGE_COMMAND_END:
2319         case LyXRC::RC_LANGUAGE_COMMAND_LOCAL:
2320         case LyXRC::RC_LANGUAGE_GLOBAL_OPTIONS:
2321         case LyXRC::RC_LANGUAGE_PACKAGE:
2322         case LyXRC::RC_LANGUAGE_USE_BABEL:
2323         case LyXRC::RC_MAKE_BACKUP:
2324         case LyXRC::RC_MARK_FOREIGN_LANGUAGE:
2325         case LyXRC::RC_NUMLASTFILES:
2326         case LyXRC::RC_PATH_PREFIX:
2327                 if (lyxrc_orig.path_prefix != lyxrc_new.path_prefix) {
2328                         support::prependEnvPath("PATH", lyxrc.path_prefix);
2329                 }
2330         case LyXRC::RC_PERS_DICT:
2331         case LyXRC::RC_PREVIEW:
2332         case LyXRC::RC_PREVIEW_HASHED_LABELS:
2333         case LyXRC::RC_PREVIEW_SCALE_FACTOR:
2334         case LyXRC::RC_PRINTCOLLCOPIESFLAG:
2335         case LyXRC::RC_PRINTCOPIESFLAG:
2336         case LyXRC::RC_PRINTER:
2337         case LyXRC::RC_PRINTEVENPAGEFLAG:
2338         case LyXRC::RC_PRINTEXSTRAOPTIONS:
2339         case LyXRC::RC_PRINTFILEEXTENSION:
2340         case LyXRC::RC_PRINTLANDSCAPEFLAG:
2341         case LyXRC::RC_PRINTODDPAGEFLAG:
2342         case LyXRC::RC_PRINTPAGERANGEFLAG:
2343         case LyXRC::RC_PRINTPAPERDIMENSIONFLAG:
2344         case LyXRC::RC_PRINTPAPERFLAG:
2345         case LyXRC::RC_PRINTREVERSEFLAG:
2346         case LyXRC::RC_PRINTSPOOL_COMMAND:
2347         case LyXRC::RC_PRINTSPOOL_PRINTERPREFIX:
2348         case LyXRC::RC_PRINTTOFILE:
2349         case LyXRC::RC_PRINTTOPRINTER:
2350         case LyXRC::RC_PRINT_ADAPTOUTPUT:
2351         case LyXRC::RC_PRINT_COMMAND:
2352         case LyXRC::RC_RTL_SUPPORT:
2353         case LyXRC::RC_SCREEN_DPI:
2354         case LyXRC::RC_SCREEN_FONT_ROMAN:
2355         case LyXRC::RC_SCREEN_FONT_ROMAN_FOUNDRY:
2356         case LyXRC::RC_SCREEN_FONT_SANS:
2357         case LyXRC::RC_SCREEN_FONT_SANS_FOUNDRY:
2358         case LyXRC::RC_SCREEN_FONT_SCALABLE:
2359         case LyXRC::RC_SCREEN_FONT_SIZES:
2360         case LyXRC::RC_SCREEN_FONT_TYPEWRITER:
2361         case LyXRC::RC_SCREEN_FONT_TYPEWRITER_FOUNDRY:
2362         case LyXRC::RC_GEOMETRY_SESSION:
2363         case LyXRC::RC_SCREEN_ZOOM:
2364         case LyXRC::RC_SERVERPIPE:
2365         case LyXRC::RC_SET_COLOR:
2366         case LyXRC::RC_SHOW_BANNER:
2367         case LyXRC::RC_SPELL_COMMAND:
2368         case LyXRC::RC_TEMPDIRPATH:
2369         case LyXRC::RC_TEMPLATEPATH:
2370         case LyXRC::RC_TEX_ALLOWS_SPACES:
2371         case LyXRC::RC_TEX_EXPECTS_WINDOWS_PATHS:
2372                 if (lyxrc_orig.windows_style_tex_paths != lyxrc_new.windows_style_tex_paths) {
2373                         support::os::windows_style_tex_paths(lyxrc_new.windows_style_tex_paths);
2374                 }
2375         case LyXRC::RC_UIFILE:
2376         case LyXRC::RC_USER_EMAIL:
2377         case LyXRC::RC_USER_NAME:
2378         case LyXRC::RC_USETEMPDIR:
2379         case LyXRC::RC_USE_ALT_LANG:
2380         case LyXRC::RC_USE_CONVERTER_CACHE:
2381         case LyXRC::RC_USE_ESC_CHARS:
2382         case LyXRC::RC_USE_INP_ENC:
2383         case LyXRC::RC_USE_PERS_DICT:
2384         case LyXRC::RC_USE_PIXMAP_CACHE:
2385         case LyXRC::RC_USE_SPELL_LIB:
2386         case LyXRC::RC_VIEWDVI_PAPEROPTION:
2387         case LyXRC::RC_SORT_LAYOUTS:
2388         case LyXRC::RC_VIEWER:
2389         case LyXRC::RC_LAST:
2390                 break;
2391         }
2392 }
2393
2394 } // namespace anon
2395
2396
2397 } // namespace lyx