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