]> git.lyx.org Git - lyx.git/blobdiff - src/lyxfunc.C
minimal effort implementation of:
[lyx.git] / src / lyxfunc.C
index f6e54aa3faf682d4d37af6ac964aedb5cdc7c024..2d1f1b65eba6fd7f58f4d55a84d040a3e31c9746 100644 (file)
@@ -43,6 +43,8 @@
 #include "kbmap.h"
 #include "language.h"
 #include "LColor.h"
+#include "session.h"
+#include "lyx_main.h"
 #include "lyx_cb.h"
 #include "LyXAction.h"
 #include "lyxfind.h"
@@ -64,6 +66,7 @@
 #include "insets/insetexternal.h"
 #include "insets/insetfloat.h"
 #include "insets/insetgraphics.h"
+#include "insets/insetinclude.h"
 #include "insets/insetnote.h"
 #include "insets/insettabular.h"
 #include "insets/insetvspace.h"
 #include "support/systemcall.h"
 #include "support/convert.h"
 #include "support/os.h"
+#include "support/unicode.h"
 
+#include <boost/current_function.hpp>
 #include <boost/filesystem/operations.hpp>
 
 #include <sstream>
 
 using bv_funcs::freefont2string;
 
-using lyx::support::AbsolutePath;
-using lyx::support::AddName;
-using lyx::support::AddPath;
+using lyx::support::absolutePath;
+using lyx::support::addName;
+using lyx::support::addPath;
 using lyx::support::bformat;
-using lyx::support::ChangeExtension;
+using lyx::support::changeExtension;
 using lyx::support::contains;
 using lyx::support::FileFilterList;
-using lyx::support::FileSearch;
+using lyx::support::fileSearch;
 using lyx::support::ForkedcallsController;
 using lyx::support::i18nLibFileSearch;
-using lyx::support::IsDirWriteable;
-using lyx::support::IsFileReadable;
+using lyx::support::isDirWriteable;
+using lyx::support::isFileReadable;
 using lyx::support::isStrInt;
-using lyx::support::MakeAbsPath;
-using lyx::support::MakeDisplayPath;
+using lyx::support::makeAbsPath;
+using lyx::support::makeDisplayPath;
 using lyx::support::package;
 using lyx::support::Path;
-using lyx::support::QuoteName;
+using lyx::support::quoteName;
 using lyx::support::rtrim;
 using lyx::support::split;
 using lyx::support::subst;
@@ -127,6 +132,7 @@ using std::make_pair;
 using std::pair;
 using std::string;
 using std::istringstream;
+using std::ostringstream;
 
 namespace biblio = lyx::biblio;
 namespace fs = boost::filesystem;
@@ -156,17 +162,9 @@ bool getStatus(LCursor cursor,
        bool res = false;
        for ( ; cursor.depth(); cursor.pop()) {
                //lyxerr << "\nLCursor::getStatus: cmd: " << cmd << endl << *this << endl;
-               DocIterator::idx_type & idx = cursor.idx();
-               DocIterator::idx_type const lastidx = cursor.lastidx();
-               BOOST_ASSERT(idx <= lastidx);
-
-               DocIterator::pit_type & pit = cursor.pit();
-               DocIterator::pit_type const lastpit = cursor.lastpit();
-               BOOST_ASSERT(pit <= lastpit);
-
-               DocIterator::pos_type & pos = cursor.pos();
-               DocIterator::pos_type const lastpos = cursor.lastpos();
-               BOOST_ASSERT(pos <= lastpos);
+               BOOST_ASSERT(cursor.idx() <= cursor.lastidx());
+               BOOST_ASSERT(cursor.pit() <= cursor.lastpit());
+               BOOST_ASSERT(cursor.pos() <= cursor.lastpos());
 
                // The inset's getStatus() will return 'true' if it made
                // a definitive decision on whether it want to handle the
@@ -180,6 +178,28 @@ bool getStatus(LCursor cursor,
        return res;
 }
 
+
+/** Return the change status at cursor position, taking in account the
+ * status at each level of the document iterator (a table in a deleted
+ * footnote is deleted).
+ * When \param outer is true, the top slice is not looked at.
+ */
+Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
+{
+       size_t const depth = dit.depth() - (outer ? 1 : 0);
+
+       for (size_t i = 0 ; i < depth ; ++i) {
+               CursorSlice const & slice = dit[i];
+               if (!slice.inset().inMathed()
+                   && slice.pos() < slice.paragraph().size()) {
+                       Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
+                       if (ch != Change::UNCHANGED)
+                               return ch;
+               }
+       }
+       return Change::UNCHANGED;
+}
+
 }
 
 LyXFunc::LyXFunc(LyXView * lv)
@@ -229,7 +249,8 @@ void LyXFunc::processKeySym(LyXKeySymPtr keysym, key_modifier::state state)
 
        Encoding const * encoding = view()->cursor().getEncoding();
 
-       encoded_last_key = keysym->getISOEncoded(encoding ? encoding->Name() : "");
+       //encoded_last_key = keysym->getISOEncoded(encoding ? encoding->name() : "");
+       size_t encoded_last_key = keysym->getUCSEncoded();
 
        // Do a one-deep top-level lookup for
        // cancel and meta-fake keys. RVDK_PATCH_5
@@ -243,7 +264,7 @@ void LyXFunc::processKeySym(LyXKeySymPtr keysym, key_modifier::state state)
        // When not cancel or meta-fake, do the normal lookup.
        // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
        // Mostly, meta_fake_bit = key_modifier::none. RVDK_PATCH_5.
-       if ((func.action != LFUN_CANCEL) && (func.action != LFUN_META_FAKE)) {
+       if ((func.action != LFUN_CANCEL) && (func.action != LFUN_META_PREFIX)) {
                // remove Caps Lock and Mod2 as a modifiers
                func = keyseq.addkey(keysym, (state | meta_fake_bit));
                lyxerr[Debug::KEY] << BOOST_CURRENT_FUNCTION
@@ -256,7 +277,7 @@ void LyXFunc::processKeySym(LyXKeySymPtr keysym, key_modifier::state state)
 
        // Can this happen now ?
        if (func.action == LFUN_NOACTION) {
-               func = FuncRequest(LFUN_PREFIX);
+               func = FuncRequest(LFUN_COMMAND_PREFIX);
        }
 
        if (lyxerr.debugging(Debug::KEY)) {
@@ -291,7 +312,8 @@ void LyXFunc::processKeySym(LyXKeySymPtr keysym, key_modifier::state state)
                // by a binding
                if (keysym->isText() && keyseq.length() == 1) {
                        lyxerr[Debug::KEY] << "isText() is true, inserting." << endl;
-                       func = FuncRequest(LFUN_SELFINSERT);
+                       func = FuncRequest(LFUN_SELF_INSERT,
+                                          FuncRequest::KEYBOARD);
                } else {
                        lyxerr[Debug::KEY] << "Unknown, !isText() - giving up" << endl;
                        owner->message(_("Unknown function."));
@@ -299,10 +321,12 @@ void LyXFunc::processKeySym(LyXKeySymPtr keysym, key_modifier::state state)
                }
        }
 
-       if (func.action == LFUN_SELFINSERT) {
+       if (func.action == LFUN_SELF_INSERT) {
                if (encoded_last_key != 0) {
-                       string const arg(1, encoded_last_key);
-                       dispatch(FuncRequest(LFUN_SELFINSERT, arg));
+                       std::vector<char> tmp = ucs4_to_utf8(encoded_last_key);
+                       string const arg(tmp.begin(), tmp.end());
+                       dispatch(FuncRequest(LFUN_SELF_INSERT, arg,
+                                            FuncRequest::KEYBOARD));
                        lyxerr[Debug::KEY]
                                << "SelfInsert arg[`" << arg << "']" << endl;
                }
@@ -322,6 +346,9 @@ FuncStatus LyXFunc::getStatus(FuncRequest const & cmd) const
           application can still be accessed without giving focus to
           the main window. In this case, we want to disable the menu
           entries that are buffer-related.
+
+          Note that this code is not perfect, as bug 1941 attests:
+          http://bugzilla.lyx.org/show_bug.cgi?id=1941#c4
        */
        Buffer * buf;
        if (cmd.origin == FuncRequest::UI && !owner->hasFocus())
@@ -377,32 +404,28 @@ FuncStatus LyXFunc::getStatus(FuncRequest const & cmd) const
                flag.setOnOff(owner->getDialogs().tooltipsEnabled());
                break;
 
-       case LFUN_READ_ONLY_TOGGLE:
+       case LFUN_BUFFER_TOGGLE_READ_ONLY:
                flag.setOnOff(buf->isReadonly());
                break;
 
-       case LFUN_SWITCHBUFFER:
+       case LFUN_BUFFER_SWITCH:
                // toggle on the current buffer, but do not toggle off
                // the other ones (is that a good idea?)
                if (cmd.argument == buf->fileName())
                        flag.setOnOff(true);
                break;
 
-       case LFUN_EXPORT:
+       case LFUN_BUFFER_EXPORT:
                enable = cmd.argument == "custom"
-                       || Exporter::IsExportable(*buf, cmd.argument);
-               break;
-       case LFUN_CUT:
-       case LFUN_COPY:
-               enable = cur.selection();
+                       || Exporter::isExportable(*buf, cmd.argument);
                break;
 
-       case LFUN_RUNCHKTEX:
+       case LFUN_BUFFER_CHKTEX:
                enable = buf->isLatex() && lyxrc.chktex_command != "none";
                break;
 
-       case LFUN_BUILDPROG:
-               enable = Exporter::IsExportable(*buf, "program");
+       case LFUN_BUILD_PROGRAM:
+               enable = Exporter::isExportable(*buf, "program");
                break;
 
        case LFUN_LAYOUT_TABULAR:
@@ -411,23 +434,23 @@ FuncStatus LyXFunc::getStatus(FuncRequest const & cmd) const
 
        case LFUN_LAYOUT:
        case LFUN_LAYOUT_PARAGRAPH:
-               enable = !cur.inset().forceDefaultParagraphs(&cur.inset());
+               enable = !cur.inset().forceDefaultParagraphs(cur.idx());
                break;
 
        case LFUN_VC_REGISTER:
                enable = !buf->lyxvc().inUse();
                break;
-       case LFUN_VC_CHECKIN:
+       case LFUN_VC_CHECK_IN:
                enable = buf->lyxvc().inUse() && !buf->isReadonly();
                break;
-       case LFUN_VC_CHECKOUT:
+       case LFUN_VC_CHECK_OUT:
                enable = buf->lyxvc().inUse() && buf->isReadonly();
                break;
        case LFUN_VC_REVERT:
-       case LFUN_VC_UNDO:
+       case LFUN_VC_UNDO_LAST:
                enable = buf->lyxvc().inUse();
                break;
-       case LFUN_MENURELOAD:
+       case LFUN_BUFFER_RELOAD:
                enable = !buf->isUnnamed() && !buf->isClean();
                break;
 
@@ -435,12 +458,7 @@ FuncStatus LyXFunc::getStatus(FuncRequest const & cmd) const
                enable = false;
                if (!cur)
                        break;
-               UpdatableInset * inset = cur.inset().asUpdatableInset();
-               lyxerr << "inset: " << inset << endl;
-               if (!inset)
-                       break;
-
-               InsetBase::Code code = inset->lyxCode();
+               InsetBase::Code code = cur.inset().lyxCode();
                switch (code) {
                        case InsetBase::TABULAR_CODE:
                                enable = cmd.argument == "tabular";
@@ -469,6 +487,24 @@ FuncStatus LyXFunc::getStatus(FuncRequest const & cmd) const
                break;
        }
 
+       case LFUN_INSET_APPLY: {
+               string const name = cmd.getArg(0);
+               InsetBase * inset = owner->getDialogs().getOpenInset(name);
+               if (inset) {
+                       FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument);
+                       FuncStatus fs;
+                       bool const success = inset->getStatus(cur, fr, fs);
+                       // Every inset is supposed to handle this
+                       BOOST_ASSERT(success);
+                       flag |= fs;
+               } else {
+                       FuncRequest fr(LFUN_INSET_INSERT, cmd.argument);
+                       flag |= getStatus(fr);
+               }
+               enable = flag.enabled();
+               break;
+       }
+
        case LFUN_DIALOG_SHOW: {
                string const name = cmd.getArg(0);
                if (!buf)
@@ -478,14 +514,20 @@ FuncStatus LyXFunc::getStatus(FuncRequest const & cmd) const
                                || name == "prefs"
                                || name == "texinfo";
                else if (name == "print")
-                       enable = Exporter::IsExportable(*buf, "dvi")
+                       enable = Exporter::isExportable(*buf, "dvi")
                                && lyxrc.print_command != "none";
                else if (name == "character" || name == "mathpanel")
                        enable = cur.inset().lyxCode() != InsetBase::ERT_CODE;
+               else if (name == "latexlog")
+                       enable = isFileReadable(buf->getLogName().second);
+#if !defined (USE_ASPELL) && !defined (USE_ISPELL) && !defined (USE_PSPELL)
+               else if (name == "spellchecker")
+                       enable = false;
+#endif
                else if (name == "vclog")
                        enable = buf->lyxvc().inUse();
-               else if (name == "latexlog")
-                       enable = IsFileReadable(buf->getLogName().second);
+               else if (name == "view-source")
+                       enable = buf;
                break;
        }
 
@@ -500,9 +542,21 @@ FuncStatus LyXFunc::getStatus(FuncRequest const & cmd) const
                break;
        }
 
+       case LFUN_CITATION_INSERT: {
+               FuncRequest fr(LFUN_INSET_INSERT, "citation");
+               enable = getStatus(fr).enabled();
+               break;
+       }
+
+       case LFUN_BUFFER_WRITE: {
+               enable = view()->buffer()->isUnnamed()
+                       || !view()->buffer()->isClean();
+               break;
+       }
+
        // this one is difficult to get right. As a half-baked
        // solution, we consider only the first action of the sequence
-       case LFUN_SEQUENCE: {
+       case LFUN_COMMAND_SEQUENCE: {
                // argument contains ';'-terminated commands
                string const firstcmd = token(cmd.argument, ';', 0);
                FuncRequest func(lyxaction.lookupFunc(firstcmd));
@@ -510,59 +564,58 @@ FuncStatus LyXFunc::getStatus(FuncRequest const & cmd) const
                flag = getStatus(func);
        }
 
-       case LFUN_MENUNEW:
-       case LFUN_MENUNEWTMPLT:
-       case LFUN_WORDFINDFORWARD:
-       case LFUN_WORDFINDBACKWARD:
-       case LFUN_PREFIX:
-       case LFUN_EXEC_COMMAND:
+       case LFUN_BUFFER_NEW:
+       case LFUN_BUFFER_NEW_TEMPLATE:
+       case LFUN_WORD_FIND_FORWARD:
+       case LFUN_WORD_FIND_BACKWARD:
+       case LFUN_COMMAND_PREFIX:
+       case LFUN_COMMAND_EXECUTE:
        case LFUN_CANCEL:
-       case LFUN_META_FAKE:
-       case LFUN_CLOSEBUFFER:
-       case LFUN_MENUWRITE:
-       case LFUN_WRITEAS:
-       case LFUN_UPDATE:
-       case LFUN_PREVIEW:
-       case LFUN_IMPORT:
-       case LFUN_QUIT:
-       case LFUN_TOCVIEW:
-       case LFUN_AUTOSAVE:
+       case LFUN_META_PREFIX:
+       case LFUN_BUFFER_CLOSE:
+       case LFUN_BUFFER_WRITE_AS:
+       case LFUN_BUFFER_UPDATE:
+       case LFUN_BUFFER_VIEW:
+       case LFUN_BUFFER_IMPORT:
+       case LFUN_LYX_QUIT:
+       case LFUN_TOC_VIEW:
+       case LFUN_BUFFER_AUTO_SAVE:
        case LFUN_RECONFIGURE:
        case LFUN_HELP_OPEN:
        case LFUN_FILE_NEW:
        case LFUN_FILE_OPEN:
        case LFUN_DROP_LAYOUTS_CHOICE:
-       case LFUN_MENU_OPEN_BY_NAME:
-       case LFUN_GETNAME:
-       case LFUN_NOTIFY:
-       case LFUN_GOTOFILEROW:
+       case LFUN_MENU_OPEN:
+       case LFUN_SERVER_GET_NAME:
+       case LFUN_SERVER_NOTIFY:
+       case LFUN_SERVER_GOTO_FILE_ROW:
        case LFUN_DIALOG_SHOW_NEXT_INSET:
        case LFUN_DIALOG_HIDE:
        case LFUN_DIALOG_DISCONNECT_INSET:
-       case LFUN_CHILDOPEN:
-       case LFUN_TOGGLECURSORFOLLOW:
-       case LFUN_KMAP_OFF:
-       case LFUN_KMAP_PRIM:
-       case LFUN_KMAP_SEC:
-       case LFUN_KMAP_TOGGLE:
+       case LFUN_BUFFER_CHILD_OPEN:
+       case LFUN_TOGGLE_CURSOR_FOLLOWS_SCROLLBAR:
+       case LFUN_KEYMAP_OFF:
+       case LFUN_KEYMAP_PRIMARY:
+       case LFUN_KEYMAP_SECONDARY:
+       case LFUN_KEYMAP_TOGGLE:
        case LFUN_REPEAT:
-       case LFUN_EXPORT_CUSTOM:
-       case LFUN_PRINT:
-       case LFUN_SAVEPREFERENCES:
+       case LFUN_BUFFER_EXPORT_CUSTOM:
+       case LFUN_BUFFER_PRINT:
+       case LFUN_PREFERENCES_SAVE:
        case LFUN_SCREEN_FONT_UPDATE:
        case LFUN_SET_COLOR:
        case LFUN_MESSAGE:
        case LFUN_EXTERNAL_EDIT:
        case LFUN_GRAPHICS_EDIT:
        case LFUN_ALL_INSETS_TOGGLE:
-       case LFUN_LANGUAGE_BUFFER:
+       case LFUN_BUFFER_LANGUAGE:
        case LFUN_TEXTCLASS_APPLY:
        case LFUN_TEXTCLASS_LOAD:
-       case LFUN_SAVE_AS_DEFAULT:
-       case LFUN_BUFFERPARAMS_APPLY:
+       case LFUN_BUFFER_SAVE_AS_DEFAULT:
+       case LFUN_BUFFER_PARAMS_APPLY:
        case LFUN_LYXRC_APPLY:
-       case LFUN_NEXTBUFFER:
-       case LFUN_PREVIOUSBUFFER:
+       case LFUN_BUFFER_NEXT:
+       case LFUN_BUFFER_PREVIOUS:
                // these are handled in our dispatch()
                break;
 
@@ -583,6 +636,15 @@ FuncStatus LyXFunc::getStatus(FuncRequest const & cmd) const
                flag.enabled(false);
        }
 
+       // Are we in a DELETED change-tracking region?
+       if (buf && buf->params().tracking_changes
+           && lookupChangeType(cur, true) == Change::DELETED
+           && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
+           && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
+               flag.message(N_("This portion of the document is deleted."));
+               flag.enabled(false);
+       }
+
        // the default error message if we disable the command
        if (!flag.enabled() && flag.message().empty())
                flag.message(N_("Command disabled"));
@@ -599,7 +661,7 @@ bool ensureBufferClean(BufferView * bv)
        if (buf.isClean())
                return true;
 
-       string const file = MakeDisplayPath(buf.fileName(), 30);
+       string const file = makeDisplayPath(buf.fileName(), 30);
        string text = bformat(_("The document %1$s has unsaved "
                                "changes.\n\nDo you want to save "
                                "the document?"), file);
@@ -608,7 +670,7 @@ bool ensureBufferClean(BufferView * bv)
                                      _("&Cancel"));
 
        if (ret == 0)
-               bv->owner()->dispatch(FuncRequest(LFUN_MENUWRITE));
+               bv->owner()->dispatch(FuncRequest(LFUN_BUFFER_WRITE));
 
        return buf.isClean();
 }
@@ -618,7 +680,7 @@ void showPrintError(string const & name)
 {
        string str = bformat(_("Could not print the document %1$s.\n"
                               "Check that your printer is set up correctly."),
-                            MakeDisplayPath(name, 50));
+                            makeDisplayPath(name, 50));
        Alert::error(_("Print document failed"), str);
 }
 
@@ -626,7 +688,7 @@ void showPrintError(string const & name)
 void loadTextclass(string const & name)
 {
        std::pair<bool, lyx::textclass_type> const tc_pair =
-               textclasslist.NumberOfClass(name);
+               textclasslist.numberOfClass(name);
 
        if (!tc_pair.first) {
                lyxerr << "Document class \"" << name
@@ -664,7 +726,11 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
        errorstat = false;
        dispatch_buffer.erase();
 
-       bool update = false;
+       // redraw the screen at the end (first of the two drawing steps).
+       //This is done unless explicitely requested otherwise
+       bool update = true;
+       // also do the second redrawing step. Only done if requested.
+       bool updateforce = false;
 
        FuncStatus const flag = getStatus(cmd);
        if (!flag.enabled()) {
@@ -675,14 +741,10 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
                       << endl;
                setErrorMessage(flag.message());
        } else {
-
-               if (view()->available())
-                       view()->hideCursor();
-
                switch (action) {
 
-               case LFUN_WORDFINDFORWARD:
-               case LFUN_WORDFINDBACKWARD: {
+               case LFUN_WORD_FIND_FORWARD:
+               case LFUN_WORD_FIND_BACKWARD: {
                        static string last_search;
                        string searched_string;
 
@@ -696,18 +758,18 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
                        if (searched_string.empty())
                                break;
 
-                       bool const fw = action == LFUN_WORDFINDFORWARD;
+                       bool const fw = action == LFUN_WORD_FIND_FORWARD;
                        string const data =
                                lyx::find::find2string(searched_string, true, false, fw);
                        lyx::find::find(view(), FuncRequest(LFUN_WORD_FIND, data));
                        break;
                }
 
-               case LFUN_PREFIX:
+               case LFUN_COMMAND_PREFIX:
                        owner->message(keyseq.printOptions());
                        break;
 
-               case LFUN_EXEC_COMMAND:
+               case LFUN_COMMAND_EXECUTE:
                        owner->getToolbars().display("minibuffer", true);
                        owner->focus_command_buffer();
                        break;
@@ -721,12 +783,12 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
                        setMessage(N_("Cancel"));
                        break;
 
-               case LFUN_META_FAKE:
+               case LFUN_META_PREFIX:
                        meta_fake_bit = key_modifier::alt;
                        setMessage(keyseq.print());
                        break;
 
-               case LFUN_READ_ONLY_TOGGLE:
+               case LFUN_BUFFER_TOGGLE_READ_ONLY:
                        if (owner->buffer()->lyxvc().inUse())
                                owner->buffer()->lyxvc().toggleReadOnly();
                        else
@@ -735,35 +797,37 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
                        break;
 
                // --- Menus -----------------------------------------------
-               case LFUN_MENUNEW:
+               case LFUN_BUFFER_NEW:
                        menuNew(argument, false);
                        break;
 
-               case LFUN_MENUNEWTMPLT:
+               case LFUN_BUFFER_NEW_TEMPLATE:
                        menuNew(argument, true);
                        break;
 
-               case LFUN_CLOSEBUFFER:
+               case LFUN_BUFFER_CLOSE:
                        closeBuffer();
                        break;
 
-               case LFUN_MENUWRITE:
+               case LFUN_BUFFER_WRITE:
                        if (!owner->buffer()->isUnnamed()) {
                                string const str = bformat(_("Saving document %1$s..."),
-                                        MakeDisplayPath(owner->buffer()->fileName()));
+                                        makeDisplayPath(owner->buffer()->fileName()));
                                owner->message(str);
-                               MenuWrite(owner->buffer());
+                               menuWrite(owner->buffer());
                                owner->message(str + _(" done."));
                        } else
-                               WriteAs(owner->buffer());
+                               writeAs(owner->buffer());
+                       update = false;
                        break;
 
-               case LFUN_WRITEAS:
-                       WriteAs(owner->buffer(), argument);
+               case LFUN_BUFFER_WRITE_AS:
+                       writeAs(owner->buffer(), argument);
+                       update = false;
                        break;
 
-               case LFUN_MENURELOAD: {
-                       string const file = MakeDisplayPath(view()->buffer()->fileName(), 20);
+               case LFUN_BUFFER_RELOAD: {
+                       string const file = makeDisplayPath(view()->buffer()->fileName(), 20);
                        string text = bformat(_("Any changes will be lost. Are you sure "
                                "you want to revert to the saved version of the document %1$s?"), file);
                        int const ret = Alert::prompt(_("Revert to saved document?"),
@@ -774,36 +838,31 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
                        break;
                }
 
-               case LFUN_UPDATE:
+               case LFUN_BUFFER_UPDATE:
                        Exporter::Export(owner->buffer(), argument, true);
-                       view()->showErrorList(BufferFormat(*owner->buffer()));
                        break;
 
-               case LFUN_PREVIEW:
-                       Exporter::Preview(owner->buffer(), argument);
-                       view()->showErrorList(BufferFormat(*owner->buffer()));
+               case LFUN_BUFFER_VIEW:
+                       Exporter::preview(owner->buffer(), argument);
                        break;
 
-               case LFUN_BUILDPROG:
+               case LFUN_BUILD_PROGRAM:
                        Exporter::Export(owner->buffer(), "program", true);
-                       view()->showErrorList(_("Build"));
                        break;
 
-               case LFUN_RUNCHKTEX:
+               case LFUN_BUFFER_CHKTEX:
                        owner->buffer()->runChktex();
-                       view()->showErrorList(_("ChkTeX"));
                        break;
 
-               case LFUN_EXPORT:
+               case LFUN_BUFFER_EXPORT:
                        if (argument == "custom")
                                owner->getDialogs().show("sendto");
                        else {
                                Exporter::Export(owner->buffer(), argument, false);
-                               view()->showErrorList(BufferFormat(*owner->buffer()));
                        }
                        break;
 
-               case LFUN_EXPORT_CUSTOM: {
+               case LFUN_BUFFER_EXPORT_CUSTOM: {
                        string format_name;
                        string command = split(argument, format_name, ' ');
                        Format const * format = formats.getFormat(format_name);
@@ -823,16 +882,15 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
                        if (format->name() == "lyx") {
                                string const latexname =
                                        buffer->getLatexName(false);
-                               filename = ChangeExtension(latexname,
+                               filename = changeExtension(latexname,
                                                           format->extension());
-                               filename = AddName(buffer->temppath(), filename);
+                               filename = addName(buffer->temppath(), filename);
 
                                if (!buffer->writeFile(filename))
                                        break;
 
                        } else {
-                               Exporter::Export(buffer, format_name, true,
-                                                filename);
+                               Exporter::Export(buffer, format_name, true, filename);
                        }
 
                        // Substitute $$FName for filename
@@ -846,7 +904,7 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
                        break;
                }
 
-               case LFUN_PRINT: {
+               case LFUN_BUFFER_PRINT: {
                        string target;
                        string target_name;
                        string command = split(split(argument, target, ' '),
@@ -883,18 +941,18 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
                        Systemcall one;
                        int res = 0;
                        string const dviname =
-                               ChangeExtension(buffer->getLatexName(true),
+                               changeExtension(buffer->getLatexName(true),
                                                "dvi");
 
                        if (target == "printer") {
                                if (!lyxrc.print_spool_command.empty()) {
                                        // case 3: print using a spool
                                        string const psname =
-                                               ChangeExtension(dviname,".ps");
+                                               changeExtension(dviname,".ps");
                                        command += lyxrc.print_to_file
-                                               + QuoteName(psname)
+                                               + quoteName(psname)
                                                + ' '
-                                               + QuoteName(dviname);
+                                               + quoteName(dviname);
 
                                        string command2 =
                                                lyxrc.print_spool_command +' ';
@@ -903,7 +961,7 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
                                                        + target_name
                                                        + ' ';
                                        }
-                                       command2 += QuoteName(psname);
+                                       command2 += quoteName(psname);
                                        // First run dvips.
                                        // If successful, then spool command
                                        res = one.startscript(
@@ -918,16 +976,16 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
                                        // case 2: print directly to a printer
                                        res = one.startscript(
                                                Systemcall::DontWait,
-                                               command + QuoteName(dviname));
+                                               command + quoteName(dviname));
                                }
 
                        } else {
                                // case 1: print to a file
                                command += lyxrc.print_to_file
-                                       + QuoteName(MakeAbsPath(target_name,
+                                       + quoteName(makeAbsPath(target_name,
                                                                path))
                                        + ' '
-                                       + QuoteName(dviname);
+                                       + quoteName(dviname);
                                res = one.startscript(Systemcall::DontWait,
                                                      command);
                        }
@@ -937,27 +995,34 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
                        break;
                }
 
-               case LFUN_IMPORT:
+               case LFUN_BUFFER_IMPORT:
                        doImport(argument);
                        break;
 
-               case LFUN_QUIT:
-                       QuitLyX();
+               case LFUN_LYX_QUIT:
+                       if (view()->available()) {
+                               // save cursor Position for opened files to .lyx/session
+                               LyX::ref().session().saveFilePosition(owner->buffer()->fileName(),
+                                       boost::tie(view()->cursor().pit(), view()->cursor().pos()) );
+                               // save bookmarks to .lyx/session
+                               view()->saveSavedPositions();
+                       }
+                       quitLyX(argument == "force");
                        break;
 
-               case LFUN_TOCVIEW: {
+               case LFUN_TOC_VIEW: {
                        InsetCommandParams p("tableofcontents");
                        string const data = InsetCommandMailer::params2string("toc", p);
                        owner->getDialogs().show("toc", data, 0);
                        break;
                }
 
-               case LFUN_AUTOSAVE:
-                       AutoSave(view());
+               case LFUN_BUFFER_AUTO_SAVE:
+                       autoSave(view());
                        break;
 
                case LFUN_RECONFIGURE:
-                       Reconfigure(view());
+                       reconfigure(view());
                        break;
 
                case LFUN_HELP_OPEN: {
@@ -973,8 +1038,8 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
                                break;
                        }
                        owner->message(bformat(_("Opening help file %1$s..."),
-                               MakeDisplayPath(fname)));
-                       view()->loadLyXFile(fname, false);
+                               makeDisplayPath(fname)));
+                       owner->loadLyXFile(fname, false);
                        break;
                }
 
@@ -988,7 +1053,7 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
                        }
                        break;
 
-               case LFUN_VC_CHECKIN:
+               case LFUN_VC_CHECK_IN:
                        if (!ensureBufferClean(view()))
                                break;
                        if (owner->buffer()->lyxvc().inUse()
@@ -998,7 +1063,7 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
                        }
                        break;
 
-               case LFUN_VC_CHECKOUT:
+               case LFUN_VC_CHECK_OUT:
                        if (!ensureBufferClean(view()))
                                break;
                        if (owner->buffer()->lyxvc().inUse()
@@ -1013,26 +1078,26 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
                        view()->reload();
                        break;
 
-               case LFUN_VC_UNDO:
+               case LFUN_VC_UNDO_LAST:
                        owner->buffer()->lyxvc().undoLast();
                        view()->reload();
                        break;
 
                // --- buffers ----------------------------------------
-               case LFUN_SWITCHBUFFER:
-                       view()->setBuffer(bufferlist.getBuffer(argument));
+               case LFUN_BUFFER_SWITCH:
+                       owner->setBuffer(bufferlist.getBuffer(argument));
                        break;
 
-               case LFUN_NEXTBUFFER:
-                       view()->setBuffer(bufferlist.next(view()->buffer()));
+               case LFUN_BUFFER_NEXT:
+                       owner->setBuffer(bufferlist.next(view()->buffer()));
                        break;
 
-               case LFUN_PREVIOUSBUFFER:
-                       view()->setBuffer(bufferlist.previous(view()->buffer()));
+               case LFUN_BUFFER_PREVIOUS:
+                       owner->setBuffer(bufferlist.previous(view()->buffer()));
                        break;
 
                case LFUN_FILE_NEW:
-                       NewFile(view(), argument);
+                       newFile(view(), argument);
                        break;
 
                case LFUN_FILE_OPEN:
@@ -1043,24 +1108,24 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
                        owner->getToolbars().openLayoutList();
                        break;
 
-               case LFUN_MENU_OPEN_BY_NAME:
+               case LFUN_MENU_OPEN:
                        owner->getMenubar().openByName(argument);
                        break;
 
                // --- lyxserver commands ----------------------------
-               case LFUN_GETNAME:
+               case LFUN_SERVER_GET_NAME:
                        setMessage(owner->buffer()->fileName());
                        lyxerr[Debug::INFO] << "FNAME["
                                                         << owner->buffer()->fileName()
                                                         << "] " << endl;
                        break;
 
-               case LFUN_NOTIFY:
+               case LFUN_SERVER_NOTIFY:
                        dispatch_buffer = keyseq.print();
                        lyxserver->notifyClient(dispatch_buffer);
                        break;
 
-               case LFUN_GOTOFILEROW: {
+               case LFUN_SERVER_GOTO_FILE_ROW: {
                        string file_name;
                        int row;
                        istringstream is(argument);
@@ -1068,16 +1133,16 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
                        if (prefixIs(file_name, package().temp_dir())) {
                                // Needed by inverse dvi search. If it is a file
                                // in tmpdir, call the apropriated function
-                               view()->setBuffer(bufferlist.getBufferFromTmp(file_name));
+                               owner->setBuffer(bufferlist.getBufferFromTmp(file_name));
                        } else {
                                // Must replace extension of the file to be .lyx
                                // and get full path
-                               string const s = ChangeExtension(file_name, ".lyx");
+                               string const s = changeExtension(file_name, ".lyx");
                                // Either change buffer or load the file
                                if (bufferlist.exists(s)) {
-                                       view()->setBuffer(bufferlist.getBuffer(s));
+                                       owner->setBuffer(bufferlist.getBuffer(s));
                                } else {
-                                       view()->loadLyXFile(s);
+                                       owner->loadLyXFile(s);
                                }
                        }
 
@@ -1085,7 +1150,6 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
 
                        view()->center();
                        // see BufferView_pimpl::center()
-                       view()->updateScrollbar();
                        break;
                }
 
@@ -1097,9 +1161,7 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
                                data = freefont2string();
                                if (!data.empty())
                                        owner->getDialogs().show("character", data);
-                       }
-
-                       else if (name == "latexlog") {
+                       } else if (name == "latexlog") {
                                pair<Buffer::LogType, string> const logfile =
                                        owner->buffer()->getLogName();
                                switch (logfile.first) {
@@ -1110,15 +1172,13 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
                                        data = "literate ";
                                        break;
                                }
-                               data += logfile.second;
+                               data += LyXLex::quoteString(logfile.second);
                                owner->getDialogs().show("log", data);
-                       }
-                       else if (name == "vclog") {
+                       } else if (name == "vclog") {
                                string const data = "vc " +
-                                       owner->buffer()->lyxvc().getLogFile();
+                                       LyXLex::quoteString(owner->buffer()->lyxvc().getLogFile());
                                owner->getDialogs().show("log", data);
-                       }
-                       else
+                       } else
                                owner->getDialogs().show(name, data);
                        break;
                }
@@ -1128,7 +1188,6 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
                        string data = trim(cmd.argument.substr(name.size()));
                        if (name == "bibitem" ||
                            name == "bibtex" ||
-                           name == "include" ||
                            name == "index" ||
                            name == "label" ||
                            name == "ref" ||
@@ -1136,6 +1195,9 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
                            name == "url") {
                                InsetCommandParams p(name);
                                data = InsetCommandMailer::params2string(name, p);
+                       } else if (name == "include") {
+                               InsetCommandParams p(data);
+                               data = InsetIncludeMailer::params2string(p);
                        } else if (name == "box") {
                                // \c data == "Boxed" || "Frameless" etc
                                InsetBoxParams p(data);
@@ -1199,17 +1261,41 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
                        owner->getDialogs().disconnect(argument);
                        break;
 
-               case LFUN_CHILDOPEN: {
+
+               case LFUN_CITATION_INSERT: {
+                       if (!argument.empty()) {
+                               // we can have one optional argument, delimited by '|'
+                               // citation-insert <key>|<text_before>
+                               // this should be enhanced to also support text_after
+                               // and citation style
+                               string arg = argument;
+                               string opt1;
+                               if (contains(argument, "|")) {
+                                       arg = token(argument, '|', 0);
+                                       opt1 = '[' + token(argument, '|', 1) + ']';
+                               }
+                               std::ostringstream os;
+                               os << "citation LatexCommand\n"
+                                  << "\\cite" << opt1 << "{" << arg << "}\n"
+                                  << "\\end_inset";
+                               FuncRequest fr(LFUN_INSET_INSERT, os.str());
+                               dispatch(fr);
+                       } else
+                               dispatch(FuncRequest(LFUN_DIALOG_SHOW, "citation"));
+                       break;
+               }
+
+               case LFUN_BUFFER_CHILD_OPEN: {
                        string const filename =
-                               MakeAbsPath(argument, owner->buffer()->filePath());
+                               makeAbsPath(argument, owner->buffer()->filePath());
                        setMessage(N_("Opening child document ") +
-                                        MakeDisplayPath(filename) + "...");
+                                        makeDisplayPath(filename) + "...");
                        view()->savePosition(0);
                        string const parentfilename = owner->buffer()->fileName();
                        if (bufferlist.exists(filename))
-                               view()->setBuffer(bufferlist.getBuffer(filename));
+                               owner->setBuffer(bufferlist.getBuffer(filename));
                        else
-                               view()->loadLyXFile(filename);
+                               owner->loadLyXFile(filename);
                        // Set the parent name of the child document.
                        // This makes insertion of citations and references in the child work,
                        // when the target is in the parent or another child document.
@@ -1217,24 +1303,24 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
                        break;
                }
 
-               case LFUN_TOGGLECURSORFOLLOW:
+               case LFUN_TOGGLE_CURSOR_FOLLOWS_SCROLLBAR:
                        lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
                        break;
 
-               case LFUN_KMAP_OFF:
-                       owner->getIntl().KeyMapOn(false);
+               case LFUN_KEYMAP_OFF:
+                       owner->getIntl().keyMapOn(false);
                        break;
 
-               case LFUN_KMAP_PRIM:
-                       owner->getIntl().KeyMapPrim();
+               case LFUN_KEYMAP_PRIMARY:
+                       owner->getIntl().keyMapPrim();
                        break;
 
-               case LFUN_KMAP_SEC:
-                       owner->getIntl().KeyMapSec();
+               case LFUN_KEYMAP_SECONDARY:
+                       owner->getIntl().keyMapSec();
                        break;
 
-               case LFUN_KMAP_TOGGLE:
-                       owner->getIntl().ToggleKeyMap();
+               case LFUN_KEYMAP_TOGGLE:
+                       owner->getIntl().toggleKeyMap();
                        break;
 
                case LFUN_REPEAT: {
@@ -1250,7 +1336,7 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
                        break;
                }
 
-               case LFUN_SEQUENCE: {
+               case LFUN_COMMAND_SEQUENCE: {
                        // argument contains ';'-terminated commands
                        string arg = argument;
                        while (!arg.empty()) {
@@ -1263,7 +1349,7 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
                        break;
                }
 
-               case LFUN_SAVEPREFERENCES: {
+               case LFUN_PREFERENCES_SAVE: {
                        Path p(package().user_support());
                        lyxrc.write("preferences", false);
                        break;
@@ -1331,6 +1417,22 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
                        break;
                }
 
+               case LFUN_INSET_APPLY: {
+                       string const name = cmd.getArg(0);
+                       InsetBase * inset = owner->getDialogs().getOpenInset(name);
+                       if (inset) {
+                               FuncRequest fr(LFUN_INSET_MODIFY, argument);
+                               inset->dispatch(view()->cursor(), fr);
+                       } else {
+                               FuncRequest fr(LFUN_INSET_INSERT, argument);
+                               dispatch(fr);
+                       }
+                       // ideally, the update flag should be set by the insets,
+                       // but this is not possible currently
+                       updateforce = true;
+                       break;
+               }
+
                case LFUN_ALL_INSETS_TOGGLE: {
                        string action;
                        string const name = split(argument, action, ' ');
@@ -1345,20 +1447,24 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
                        InsetIterator const end = inset_iterator_end(inset);
                        for (; it != end; ++it) {
                                if (inset_code == InsetBase::NO_CODE
-                                   || inset_code == it->lyxCode())
-                                       it->dispatch(cur, fr);
+                                   || inset_code == it->lyxCode()) {
+                                       LCursor tmpcur = cur;
+                                       tmpcur.pushLeft(*it);
+                                       it->dispatch(tmpcur, fr);
+                               }
                        }
+                       updateforce = true;
                        break;
                }
 
-               case LFUN_LANGUAGE_BUFFER: {
+               case LFUN_BUFFER_LANGUAGE: {
                        Buffer & buffer = *owner->buffer();
                        Language const * oldL = buffer.params().language;
                        Language const * newL = languages.getLanguage(argument);
                        if (!newL || oldL == newL)
                                break;
 
-                       if (oldL->RightToLeft() == newL->RightToLeft()
+                       if (oldL->rightToLeft() == newL->rightToLeft()
                            && !buffer.isMultiLingual())
                                buffer.changeLanguage(oldL, newL);
                        else
@@ -1366,9 +1472,9 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
                        break;
                }
 
-               case LFUN_SAVE_AS_DEFAULT: {
+               case LFUN_BUFFER_SAVE_AS_DEFAULT: {
                        string const fname =
-                               AddName(AddPath(package().user_support(), "templates/"),
+                               addName(addPath(package().user_support(), "templates/"),
                                        "defaults.lyx");
                        Buffer defaults(fname);
 
@@ -1378,7 +1484,7 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
                        int const unknown_tokens = defaults.readHeader(lex);
 
                        if (unknown_tokens != 0) {
-                               lyxerr << "Warning in LFUN_SAVE_AS_DEFAULT!\n"
+                               lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
                                       << unknown_tokens << " unknown token"
                                       << (unknown_tokens == 1 ? "" : "s")
                                       << endl;
@@ -1386,13 +1492,13 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
 
                        if (defaults.writeFile(defaults.fileName()))
                                setMessage(_("Document defaults saved in ")
-                                          + MakeDisplayPath(fname));
+                                          + makeDisplayPath(fname));
                        else
                                setErrorMessage(_("Unable to save document defaults"));
                        break;
                }
 
-               case LFUN_BUFFERPARAMS_APPLY: {
+               case LFUN_BUFFER_PARAMS_APPLY: {
                        biblio::CiteEngine const engine =
                                owner->buffer()->params().cite_engine;
 
@@ -1403,7 +1509,7 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
                                owner->buffer()->readHeader(lex);
 
                        if (unknown_tokens != 0) {
-                               lyxerr << "Warning in LFUN_BUFFERPARAMS_APPLY!\n"
+                               lyxerr << "Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
                                       << unknown_tokens << " unknown token"
                                       << (unknown_tokens == 1 ? "" : "s")
                                       << endl;
@@ -1432,7 +1538,7 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
                        loadTextclass(argument);
 
                        std::pair<bool, lyx::textclass_type> const tc_pair =
-                               textclasslist.NumberOfClass(argument);
+                               textclasslist.numberOfClass(argument);
 
                        if (!tc_pair.first)
                                break;
@@ -1443,13 +1549,19 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
                                break;
 
                        owner->message(_("Converting document to new document class..."));
-                       ErrorList el;
-                       lyx::cap::SwitchLayoutsBetweenClasses(
+                       recordUndoFullDocument(view());
+                       buffer->params().textclass = new_class;
+                       StableDocIterator backcur(view()->cursor());
+                       ErrorList & el = buffer->errorList("Class Switch");
+                       lyx::cap::switchBetweenClasses(
                                old_class, new_class,
-                               buffer->paragraphs(), el);
+                               static_cast<InsetText &>(buffer->inset()), el);
+
+                       view()->setCursor(backcur.asDocIterator(&(buffer->inset())));
 
-                       bufferErrors(*buffer, el);
-                       view()->showErrorList(_("Class switch"));
+                       buffer->errors("Class Switch");
+                       updateLabels(*buffer);
+                       updateforce = true;
                        break;
                }
 
@@ -1476,11 +1588,9 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
 
                default: {
                        view()->cursor().dispatch(cmd);
-                       update |= view()->cursor().result().update();
-                       if (!view()->cursor().result().dispatched()) {
-                               update |= view()->dispatch(cmd);
-                       }
-
+                       updateforce |= view()->cursor().result().update();
+                       if (!view()->cursor().result().dispatched())
+                               updateforce |= view()->dispatch(cmd);
                        break;
                }
                }
@@ -1489,32 +1599,45 @@ void LyXFunc::dispatch(FuncRequest const & cmd)
                        // Redraw screen unless explicitly told otherwise.
                        // This also initializes the position cache for all insets
                        // in (at least partially) visible top-level paragraphs.
-                       view()->update(true, update);
+                       if (updateforce)
+                               view()->update(Update::FitCursor | Update::Force);
+                       else if (update)
+                               view()->update(Update::FitCursor);
+
+                       owner->redrawWorkArea();
 
                        // if we executed a mutating lfun, mark the buffer as dirty
-                       if (getStatus(cmd).enabled()
-                                       && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)
-                                       && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly))
+                       if (flag.enabled()
+                           && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)
+                           && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly))
                                view()->buffer()->markDirty();
-               }
 
-               if (view()->cursor().inTexted()) {
-                       view()->owner()->updateLayoutChoice();
+                       if (view()->cursor().inTexted()) {
+                               view()->owner()->updateLayoutChoice();
+                       }
                }
        }
-       sendDispatchMessage(getMessage(), cmd);
+       if (!quitting)
+               sendDispatchMessage(_(getMessage()), cmd);
 }
 
 
 void LyXFunc::sendDispatchMessage(string const & msg, FuncRequest const & cmd)
 {
-       owner->updateMenubar();
-       owner->updateToolbars();
+       /* When an action did not originate from the UI/kbd, it makes
+        * sense to avoid updating the GUI. It turns out that this
+        * fixes bug 1941, for reasons that are described here:
+        * http://bugzilla.lyx.org/show_bug.cgi?id=1941#c4
+        */
+       if (cmd.origin != FuncRequest::INTERNAL) {
+               owner->updateMenubar();
+               owner->updateToolbars();
+       }
 
        const bool verbose = (cmd.origin == FuncRequest::UI
                              || cmd.origin == FuncRequest::COMMANDBUFFER);
 
-       if (cmd.action == LFUN_SELFINSERT || !verbose) {
+       if (cmd.action == LFUN_SELF_INSERT || !verbose) {
                lyxerr[Debug::ACTION] << "dispatch msg is " << msg << endl;
                if (!msg.empty())
                        owner->message(msg);
@@ -1538,15 +1661,14 @@ void LyXFunc::sendDispatchMessage(string const & msg, FuncRequest const & cmd)
 
        string const shortcuts = toplevel_keymap->printbindings(cmd);
 
-       if (!shortcuts.empty()) {
+       if (!shortcuts.empty())
                comname += ": " + shortcuts;
-       } else if (!argsadded && !cmd.argument.empty()) {
+       else if (!argsadded && !cmd.argument.empty())
                comname += ' ' + cmd.argument;
-       }
 
        if (!comname.empty()) {
                comname = rtrim(comname);
-               dispatch_msg += '(' + comname + ')';
+               dispatch_msg += '(' + rtrim(comname) + ')';
        }
 
        lyxerr[Debug::ACTION] << "verbose dispatch msg " << dispatch_msg << endl;
@@ -1572,18 +1694,18 @@ void LyXFunc::menuNew(string const & name, bool fromTemplate)
        if (view()->available()) {
                string const trypath = owner->buffer()->filePath();
                // If directory is writeable, use this as default.
-               if (IsDirWriteable(trypath))
+               if (isDirWriteable(trypath))
                        initpath = trypath;
        }
 
        static int newfile_number;
 
        if (filename.empty()) {
-               filename = AddName(lyxrc.document_path,
+               filename = addName(lyxrc.document_path,
                            "newfile" + convert<string>(++newfile_number) + ".lyx");
                while (bufferlist.exists(filename) || fs::is_readable(filename)) {
                        ++newfile_number;
-                       filename = AddName(lyxrc.document_path,
+                       filename = addName(lyxrc.document_path,
                                           "newfile" +  convert<string>(newfile_number) +
                                    ".lyx");
                }
@@ -1611,7 +1733,9 @@ void LyXFunc::menuNew(string const & name, bool fromTemplate)
                templname = result.second;
        }
 
-       view()->newFile(filename, templname, !name.empty());
+       Buffer * const b = newFile(filename, templname, !name.empty());
+       if (b)
+               owner->setBuffer(b);
 }
 
 
@@ -1622,7 +1746,7 @@ void LyXFunc::open(string const & fname)
        if (view()->available()) {
                string const trypath = owner->buffer()->filePath();
                // If directory is writeable, use this as default.
-               if (IsDirWriteable(trypath))
+               if (isDirWriteable(trypath))
                        initpath = trypath;
        }
 
@@ -1634,7 +1758,7 @@ void LyXFunc::open(string const & fname)
                        make_pair(string(_("Documents|#o#O")),
                                  string(lyxrc.document_path)),
                        make_pair(string(_("Examples|#E#e")),
-                                 string(AddPath(package().system_support(), "examples"))));
+                                 string(addPath(package().system_support(), "examples"))));
 
                FileDialog::Result result =
                        fileDlg.open(initpath,
@@ -1656,24 +1780,26 @@ void LyXFunc::open(string const & fname)
 
        // get absolute path of file and add ".lyx" to the filename if
        // necessary
-       string const fullpath = FileSearch(string(), filename, "lyx");
+       string const fullpath = fileSearch(string(), filename, "lyx");
        if (!fullpath.empty()) {
                filename = fullpath;
        }
 
-       string const disp_fn(MakeDisplayPath(filename));
+       string const disp_fn(makeDisplayPath(filename));
 
        // if the file doesn't exist, let the user create one
        if (!fs::exists(filename)) {
-               // the user specifically chose this name. Believe them.
-               view()->newFile(filename, "", true);
+               // the user specifically chose this name. Believe him.
+               Buffer * const b = newFile(filename, string(), true);
+               if (b)
+                       owner->setBuffer(b);
                return;
        }
 
        owner->message(bformat(_("Opening document %1$s..."), disp_fn));
 
        string str2;
-       if (view()->loadLyXFile(filename)) {
+       if (owner->loadLyXFile(filename)) {
                str2 = bformat(_("Document %1$s opened."), disp_fn);
        } else {
                str2 = bformat(_("Could not open document %1$s"), disp_fn);
@@ -1697,7 +1823,7 @@ void LyXFunc::doImport(string const & argument)
                if (view()->available()) {
                        string const trypath = owner->buffer()->filePath();
                        // If directory is writeable, use this as default.
-                       if (IsDirWriteable(trypath))
+                       if (isDirWriteable(trypath))
                                initpath = trypath;
                }
 
@@ -1705,11 +1831,11 @@ void LyXFunc::doImport(string const & argument)
                        formats.prettyName(format));
 
                FileDialog fileDlg(text,
-                       LFUN_IMPORT,
+                       LFUN_BUFFER_IMPORT,
                        make_pair(string(_("Documents|#o#O")),
                                  string(lyxrc.document_path)),
                        make_pair(string(_("Examples|#E#e")),
-                                 string(AddPath(package().system_support(), "examples"))));
+                                 string(addPath(package().system_support(), "examples"))));
 
                string const filter = formats.prettyName(format)
                        + " (*." + formats.extension(format) + ')';
@@ -1733,9 +1859,9 @@ void LyXFunc::doImport(string const & argument)
                return;
 
        // get absolute path of file
-       filename = MakeAbsPath(filename);
+       filename = makeAbsPath(filename);
 
-       string const lyxfile = ChangeExtension(filename, ".lyx");
+       string const lyxfile = changeExtension(filename, ".lyx");
 
        // Check if the document already is open
        if (lyx_gui::use_gui && bufferlist.exists(lyxfile)) {
@@ -1748,7 +1874,7 @@ void LyXFunc::doImport(string const & argument)
        // if the file exists already, and we didn't do
        // -i lyx thefile.lyx, warn
        if (fs::exists(lyxfile) && filename != lyxfile) {
-               string const file = MakeDisplayPath(lyxfile, 30);
+               string const file = makeDisplayPath(lyxfile, 30);
 
                string text = bformat(_("The document %1$s already exists.\n\n"
                        "Do you want to over-write that document?"), file);
@@ -1761,12 +1887,17 @@ void LyXFunc::doImport(string const & argument)
                }
        }
 
-       Importer::Import(owner, filename, format);
+       ErrorList errorList;
+       Importer::Import(owner, filename, format, errorList);
+       // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
 }
 
 
 void LyXFunc::closeBuffer()
 {
+       // save current cursor position
+       LyX::ref().session().saveFilePosition(owner->buffer()->fileName(),
+               boost::tie(view()->cursor().pit(), view()->cursor().pos()) );
        if (bufferlist.close(owner->buffer(), true) && !quitting) {
                if (bufferlist.empty()) {
                        // need this otherwise SEGV may occur while
@@ -1774,7 +1905,7 @@ void LyXFunc::closeBuffer()
                        // since there's no current buffer
                        owner->getDialogs().hideBufferDependent();
                } else {
-                       view()->setBuffer(bufferlist.first());
+                       owner->setBuffer(bufferlist.first());
                }
        }
 }
@@ -1820,7 +1951,7 @@ string const LyXFunc::viewStatusMessage()
 BufferView * LyXFunc::view() const
 {
        BOOST_ASSERT(owner);
-       return owner->view().get();
+       return owner->view();
 }
 
 
@@ -1853,17 +1984,14 @@ void actOnUpdatedPrefs(LyXRC const & lyxrc_orig, LyXRC const & lyxrc_new)
        case LyXRC::RC_BIBTEX_COMMAND:
        case LyXRC::RC_BINDFILE:
        case LyXRC::RC_CHECKLASTFILES:
+       case LyXRC::RC_USELASTFILEPOS:
+       case LyXRC::RC_LOADSESSION:
        case LyXRC::RC_CHKTEX_COMMAND:
        case LyXRC::RC_CONVERTER:
        case LyXRC::RC_COPIER:
        case LyXRC::RC_CURSOR_FOLLOWS_SCROLLBAR:
        case LyXRC::RC_CUSTOM_EXPORT_COMMAND:
        case LyXRC::RC_CUSTOM_EXPORT_FORMAT:
-       case LyXRC::RC_CYGWIN_PATH_FIX:
-               if (lyxrc_orig.cygwin_path_fix != lyxrc_new.cygwin_path_fix) {
-                       namespace os = lyx::support::os;
-                       os::cygwin_path_fix(lyxrc_new.cygwin_path_fix);
-               }
        case LyXRC::RC_DATE_INSERT_FORMAT:
        case LyXRC::RC_DEFAULT_LANGUAGE:
        case LyXRC::RC_DEFAULT_PAPERSIZE:
@@ -1894,7 +2022,6 @@ void actOnUpdatedPrefs(LyXRC const & lyxrc_orig, LyXRC const & lyxrc_new)
        case LyXRC::RC_LANGUAGE_GLOBAL_OPTIONS:
        case LyXRC::RC_LANGUAGE_PACKAGE:
        case LyXRC::RC_LANGUAGE_USE_BABEL:
-       case LyXRC::RC_LASTFILES:
        case LyXRC::RC_MAKE_BACKUP:
        case LyXRC::RC_MARK_FOREIGN_LANGUAGE:
        case LyXRC::RC_NUMLASTFILES:
@@ -1939,6 +2066,9 @@ void actOnUpdatedPrefs(LyXRC const & lyxrc_orig, LyXRC const & lyxrc_new)
        case LyXRC::RC_SCREEN_FONT_SIZES:
        case LyXRC::RC_SCREEN_FONT_TYPEWRITER:
        case LyXRC::RC_SCREEN_FONT_TYPEWRITER_FOUNDRY:
+       case LyXRC::RC_SCREEN_GEOMETRY_HEIGHT:
+       case LyXRC::RC_SCREEN_GEOMETRY_WIDTH:
+       case LyXRC::RC_SCREEN_GEOMETRY_XYSAVED:
        case LyXRC::RC_SCREEN_ZOOM:
        case LyXRC::RC_SERVERPIPE:
        case LyXRC::RC_SET_COLOR:
@@ -1946,6 +2076,12 @@ void actOnUpdatedPrefs(LyXRC const & lyxrc_orig, LyXRC const & lyxrc_new)
        case LyXRC::RC_SPELL_COMMAND:
        case LyXRC::RC_TEMPDIRPATH:
        case LyXRC::RC_TEMPLATEPATH:
+       case LyXRC::RC_TEX_ALLOWS_SPACES:
+       case LyXRC::RC_TEX_EXPECTS_WINDOWS_PATHS:
+               if (lyxrc_orig.windows_style_tex_paths != lyxrc_new.windows_style_tex_paths) {
+                       namespace os = lyx::support::os;
+                       os::windows_style_tex_paths(lyxrc_new.windows_style_tex_paths);
+               }
        case LyXRC::RC_UIFILE:
        case LyXRC::RC_USER_EMAIL:
        case LyXRC::RC_USER_NAME:
@@ -1957,7 +2093,6 @@ void actOnUpdatedPrefs(LyXRC const & lyxrc_orig, LyXRC const & lyxrc_new)
        case LyXRC::RC_USE_SPELL_LIB:
        case LyXRC::RC_VIEWDVI_PAPEROPTION:
        case LyXRC::RC_VIEWER:
-       case LyXRC::RC_WHEEL_JUMP:
        case LyXRC::RC_LAST:
                break;
        }