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