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