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