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