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