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