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