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