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