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