]> git.lyx.org Git - lyx.git/blobdiff - src/lyxfunc.C
Small fixes
[lyx.git] / src / lyxfunc.C
index 02c3c25452c374d707e9b2a6b9ae08e9e555273c..242c756850c9da2d917b4c53fa1b3c6b23d19fcf 100644 (file)
 
 #include <config.h>
 
-#ifdef HAVE_SSTREAM
-#include <sstream>
-using std::istringstream;
-#else
-#include <strstream>
-#endif
+#include "Lsstream.h"
 
 #include <time.h>
 #include <locale.h>
@@ -28,7 +23,7 @@ using std::istringstream;
 #pragma implementation
 #endif
 
-#include "lyxlookup.h"
+#include "version.h"
 #include "kbmap.h"
 #include "lyxfunc.h"
 #include "bufferlist.h"
@@ -42,9 +37,6 @@ using std::istringstream;
 #include "insets/inseturl.h"
 #include "insets/insetlatexaccent.h"
 #include "insets/insettoc.h"
-#include "insets/insetlof.h"
-#include "insets/insetloa.h"
-#include "insets/insetlot.h"
 #include "insets/insetref.h"
 #include "insets/insetparent.h"
 #include "insets/insetindex.h"
@@ -56,9 +48,14 @@ using std::istringstream;
 #include "insets/insetexternal.h"
 #include "insets/insetgraphics.h"
 #include "insets/insetfoot.h"
+#include "insets/insetmarginal.h"
+#include "insets/insetminipage.h"
+#include "insets/insetfloat.h"
+#include "insets/insetlist.h"
 #include "insets/insettabular.h"
+#include "insets/insettheorem.h"
+#include "insets/insetcaption.h"
 #include "mathed/formulamacro.h"
-#include "toolbar.h"
 #include "spellchecker.h" // RVDK_PATCH_5
 #include "minibuffer.h"
 #include "vspace.h"
@@ -70,73 +67,49 @@ using std::istringstream;
 #include "support/syscall.h"
 #include "support/lstrings.h"
 #include "support/path.h"
+#include "support/lyxfunctional.h"
 #include "debug.h"
 #include "lyxrc.h"
 #include "lyxtext.h"
 #include "gettext.h"
 #include "trans_mgr.h"
-#include "ImportLaTeX.h"
-#include "ImportNoweb.h"
 #include "layout.h"
 #include "WorkArea.h"
 #include "lyxfr1.h"
-#include "menus.h"
 #include "bufferview_funcs.h"
 #include "frontends/Dialogs.h"
+#include "frontends/Toolbar.h"
+#include "frontends/Menubar.h"
+#include "FloatList.h"
+#include "converter.h"
+#include "exporter.h"
+#include "importer.h"
+#include "FontLoader.h"
+#include "TextCache.h"
 
 using std::pair;
 using std::endl;
+using std::find_if;
 
-extern bool cursor_follows_scrollbar;
-
-extern void InsertAsciiFile(BufferView *, string const &, bool);
-extern void math_insert_symbol(char const *);
-extern Bool math_insert_greek(char const); // why "Bool"?
+extern void math_insert_symbol(string const &);
+extern bool math_insert_greek(char);
 extern BufferList bufferlist;
 extern LyXServer * lyxserver;
-extern short greek_kb_flag;
-extern FD_form_toc * fd_form_toc;
+extern int greek_kb_flag;
 extern bool selection_possible;
 
 extern kb_keymap * toplevel_keymap;
 
-extern void MenuWrite(Buffer *);
-extern void MenuWriteAs(Buffer *);
-extern int  MenuRunLaTeX(Buffer *);
-extern int  MenuBuildProg(Buffer *);
-extern int  MenuRunChktex(Buffer *);
-extern bool CreatePostscript(Buffer *, bool);
-extern void MenuPrint(Buffer *);
-extern void MenuSendto();
-extern void QuitLyX();
+#if 0
 extern void MenuFax(Buffer *);
-extern void MenuExport(Buffer *, string const &);
+#endif
+extern void show_symbols_form(LyXFunc *);
 
 extern LyXAction lyxaction;
 // (alkis)
 extern tex_accent_struct get_accent(kb_action action);
 
-extern void AutoSave(BufferView *);
-extern bool PreviewDVI(Buffer *);
-extern bool PreviewPostscript(Buffer *);
-extern void MenuInsertLabel(char const *);
-extern void MenuInsertRef();
-extern void MenuLayoutCharacter();
-extern void MenuLayoutParagraph();
-extern void MenuLayoutDocument();
-extern void MenuLayoutPaper();
-extern void MenuLayoutTable(int flag);
-extern void MenuLayoutQuotes();
-extern void MenuLayoutPreamble();
-extern void MenuLayoutSave();
-extern void bulletForm();
-
-extern Buffer * NewLyxFile(string const &);
-extern void LoadLyXFile(string const &);
-extern void Reconfigure(BufferView *);
-
 extern LyXTextClass::size_type current_layout;
-extern int getISOCodeFromLaTeX(char *);
 
 extern void ShowLatexLog();
 
@@ -172,79 +145,74 @@ void LyXFunc::moveCursorUpdate(bool selecting)
        
        /* ---> Everytime the cursor is moved, show the current font state. */
        // should this too me moved out of this func?
-       //owner->getMiniBuffer()->Set(CurrentState());
+       //owner->showState();
        owner->view()->setState();
 }
 
 
-int LyXFunc::processKeyEvent(XEvent * ev)
+int LyXFunc::processKeySym(KeySym keysym, unsigned int state) 
 {
-       char s_r[10];
        string argument;
-       XKeyEvent * keyevent = &ev->xkey;
-       KeySym keysym_return = 0;
-
-       int num_bytes = LyXLookupString(ev, s_r, 10, &keysym_return);
-       s_r[num_bytes] = '\0';
-
+       
        if (lyxerr.debugging(Debug::KEY)) {
-               char * tmp = XKeysymToString(keysym_return);
+               char * tmp = XKeysymToString(keysym);
                string stm = (tmp ? tmp : "");
                lyxerr << "KeySym is "
                       << stm
                       << "["
-                      << keysym_return << "]"
-                      << " and num_bytes is "
-                      << num_bytes
-                      << " the string returned is \""
-                      << s_r << '\"' << endl;
+                      << keysym << "]"
+                      << endl;
        }
        // Do nothing if we have nothing (JMarc)
-       if (num_bytes == 0 && keysym_return == NoSymbol) {
+       if (keysym == NoSymbol) {
                lyxerr[Debug::KEY] << "Empty kbd action (probably composing)"
                                   << endl;
-               return 0;
+               //return 0;
+               return FL_PREEMPT;
        }
-       
-       // this function should be used always [asierra060396]
-       UpdatableInset * tli = owner->view()->the_locking_inset;
-       if (owner->view()->available() && tli && (keysym_return==XK_Escape)) {
-               if (tli == tli->GetLockingInset()) {
-                       owner->view()->unlockInset(tli);
-                       owner->view()->text->CursorRight(owner->view());
-                       moveCursorUpdate(false);
-                       owner->getMiniBuffer()->Set(CurrentState(owner->view()));
-               } else {
-                       tli->UnlockInsetInInset(owner->view(),
-                                               tli->GetLockingInset(),true);
+
+       if (owner->view()->available()) {
+               // this function should be used always [asierra060396]
+               UpdatableInset * tli = owner->view()->theLockingInset();
+               if (tli && (keysym == XK_Escape)) {
+                       if (tli == tli->GetLockingInset()) {
+                               owner->view()->unlockInset(tli);
+                               owner->view()->text->CursorRight(owner->view());
+                               moveCursorUpdate(false);
+                               owner->showState();
+                       } else {
+                               tli->UnlockInsetInInset(owner->view(),
+                                                       tli->GetLockingInset(),true);
+                       }
+                       //return 0;
+                       return FL_PREEMPT;
                }
-               return 0;
        }
-
+       
        // Can we be sure that this will work for all X-Windows
        // implementations? (Lgb)
        // This code snippet makes lyx ignore some keys. Perhaps
        // all of them should be explictly mentioned?
-       if((keysym_return >= XK_Shift_L && keysym_return <= XK_Hyper_R)
-          || keysym_return == XK_Mode_switch || keysym_return == 0x0)
+       if ((keysym >= XK_Shift_L && keysym <= XK_Hyper_R)
+          || keysym == XK_Mode_switch || keysym == 0x0)
                return 0;
 
        // Do a one-deep top-level lookup for
        // cancel and meta-fake keys. RVDK_PATCH_5
        cancel_meta_seq.reset();
 
-       int action = cancel_meta_seq.addkey(keysym_return, keyevent->state
+       int action = cancel_meta_seq.addkey(keysymstate
                                            &(ShiftMask|ControlMask
                                              |Mod1Mask)); 
 
        // 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 = 0. RVDK_PATCH_5.
-       if ( (action != LFUN_CANCEL) && (action != LFUN_META_FAKE) ) {
+       if ((action != LFUN_CANCEL) && (action != LFUN_META_FAKE)) {
 
                // remove Caps Lock and Mod2 as a modifiers
-               action = keyseq.addkey(keysym_return,
-                                      (keyevent->state | meta_fake_bit)
+               action = keyseq.addkey(keysym,
+                                      (state | meta_fake_bit)
                                       &(ShiftMask|ControlMask
                                         |Mod1Mask));      
        }
@@ -258,15 +226,15 @@ int LyXFunc::processKeyEvent(XEvent * ev)
                keyseq.print(buf);
                lyxerr << "Key ["
                       << action << "]["
-                      << buf << "]["
-                      << num_bytes << "]" << endl;
+                      << buf << "]"
+                      << endl;
        }
 
        // already here we know if it any point in going further
        // why not return already here if action == -1 and
        // num_bytes == 0? (Lgb)
 
-       if(keyseq.length > 1 || keyseq.length < -1) {
+       if (keyseq.length > 1 || keyseq.length < -1) {
                string buf;
                keyseq.print(buf);
                owner->getMiniBuffer()->Set(buf);
@@ -282,9 +250,9 @@ int LyXFunc::processKeyEvent(XEvent * ev)
                }
        
                char isochar = keyseq.getiso();
-               if (!(keyevent->state&ControlMask) &&
-                   !(keyevent->state&Mod1Mask) &&
-                   (isochar && keysym_return < 0xF000)) {
+               if (!(state & ControlMask) &&
+                   !(state & Mod1Mask) &&
+                   (isochar && keysym < 0xF000)) {
                        argument += isochar;
                }
                if (argument.empty()) {
@@ -293,14 +261,11 @@ int LyXFunc::processKeyEvent(XEvent * ev)
                        // so we`ll skip the dispatch.
                        return 0;
                }
-       } else
-               if (action == LFUN_SELFINSERT) {
-                       argument = s_r[0];
-               }
-    
+       }
+
         bool tmp_sc = show_sc;
        show_sc = false;
-       Dispatch(action, argument.c_str());
+       Dispatch(action, argument);
        show_sc = tmp_sc;
        
        return 0;
@@ -342,49 +307,29 @@ LyXFunc::func_status LyXFunc::getStatus(int ac) const
                        setErrorMessage(N_("Command not allowed with"
                                           "out any document open"));
                        flag |= LyXFunc::Disabled;
+                       return flag;
                }
        }
 
-       if (flag & LyXFunc::Disabled)
-               return flag;
-
        // I would really like to avoid having this switch and rather try to
        // encode this in the function itself.
-        static bool noLaTeX = lyxrc.latex_command == "none";
         bool disable = false;
         switch (action) {
-       case LFUN_PREVIEW:
-               disable = noLaTeX || lyxrc.view_dvi_command == "none";
-               break;
-       case LFUN_PREVIEWPS:
-               disable = noLaTeX || lyxrc.view_ps_command == "none";
-               break;
-       case LFUN_RUNLATEX:
-       case LFUN_RUNDVIPS:
-               disable = noLaTeX;
-               break;
        case LFUN_MENUPRINT:
-               disable = noLaTeX || lyxrc.print_command == "none";
+               disable = !Exporter::IsExportable(buf, "dvi")
+                       || lyxrc.print_command == "none";
                break;
+#if 0
        case LFUN_FAX:
-               disable = noLaTeX || lyxrc.fax_command == "none";
-               break;
-       case LFUN_IMPORT:
-               if (argument == "latex")
-                       disable = lyxrc.relyx_command == "none";
-               if (argument == "linuxdoc")
-                       disable = lyxrc.linuxdoc_to_lyx_command == "none";
+               disable = !Exporter::IsExportable(buf, "ps")
+                       || lyxrc.fax_command == "none";
                break;
+#else
        case LFUN_EXPORT:
-               if (argument == "dvi" || argument == "postscript")
-                       disable = noLaTeX;
-               if (argument == "html")
-                       disable = lyxrc.html_command == "none";
-               if (argument == "html-linuxdoc")
-                       disable = lyxrc.linuxdoc_to_html_command == "none";
-               if (argument == "html-docbook")
-                       disable = lyxrc.docbook_to_html_command == "none";
+               disable = argument == "fax" &&
+                       !Exporter::IsExportable(buf, argument);
                break;
+#endif
        case LFUN_UNDO:
                disable = buf->undostack.empty();
                break;
@@ -397,8 +342,73 @@ LyXFunc::func_status LyXFunc::getStatus(int ac) const
        case LFUN_RUNCHKTEX:
                disable = lyxrc.chktex_command == "none";
                break;
-       case LFUN_LAYOUT_TABLE:
-               disable = ! owner->view()->text->cursor.par()->table;
+       case LFUN_BUILDPROG:
+               disable = !Exporter::IsExportable(buf, "program");
+               break;
+
+       case LFUN_INSERTFOOTNOTE:
+       case LFUN_FOOTMELT:
+       case LFUN_MARGINMELT:
+               // Disable insertion of floats in a tabular.
+               disable = false;
+               if (owner->view()->theLockingInset()) {
+                       disable = (owner->view()->theLockingInset()->LyxCode() == Inset::TABULAR_CODE) ||
+                               owner->view()->theLockingInset()->GetFirstLockingInsetOfType(Inset::TABULAR_CODE);
+               }
+               break;
+
+       case LFUN_LAYOUT_TABULAR:
+               disable = true;
+               if (owner->view()->theLockingInset()) {
+                       disable = (owner->view()->theLockingInset()->LyxCode() != Inset::TABULAR_CODE) &&
+                               !owner->view()->theLockingInset()->GetFirstLockingInsetOfType(Inset::TABULAR_CODE);
+               }
+               break;
+
+       case LFUN_TABULAR_FEATURE:
+               disable = true;
+               if (owner->view()->theLockingInset()) {
+                       func_status ret = LyXFunc::Disabled;
+                       if (owner->view()->theLockingInset()->LyxCode() == Inset::TABULAR_CODE) {
+                               ret = static_cast<InsetTabular *>
+                                       (owner->view()->theLockingInset())->
+                                       getStatus(argument);
+                       } else if (owner->view()->theLockingInset()->GetFirstLockingInsetOfType(Inset::TABULAR_CODE)) {
+                               ret = static_cast<InsetTabular *>
+                                       (owner->view()->theLockingInset()->
+                                       GetFirstLockingInsetOfType(Inset::TABULAR_CODE))->
+                                       getStatus(argument);
+                       }
+                       flag |= ret;
+                       disable = false;
+               } else {
+                   static InsetTabular inset(*owner->buffer(), 1, 1);
+                   func_status ret;
+
+                   disable = true;
+                   ret = inset.getStatus(argument);
+                   if ((ret & LyXFunc::ToggleOn) ||
+                       (ret & LyXFunc::ToggleOff))
+                       flag |= LyXFunc::ToggleOff;
+               }
+               break;
+
+       case LFUN_VC_REGISTER:
+               disable = buf->lyxvc.inUse();
+               break;
+       case LFUN_VC_CHECKIN:
+               disable = !buf->lyxvc.inUse() || buf->isReadonly();
+               break;
+       case LFUN_VC_CHECKOUT:
+               disable = !buf->lyxvc.inUse() || !buf->isReadonly();
+               break;
+       case LFUN_VC_REVERT:
+       case LFUN_VC_UNDO:
+       case LFUN_VC_HISTORY:
+               disable = !buf->lyxvc.inUse();
+               break;
+       case LFUN_REF_BACK:
+               disable = owner->view()->NoSavedPositions();
                break;
        default:
                break;
@@ -408,7 +418,13 @@ LyXFunc::func_status LyXFunc::getStatus(int ac) const
 
        if (buf) {
                func_status box = LyXFunc::ToggleOff;
-               LyXFont font = owner->view()->text->real_current_font;
+               LyXFont font;
+               if (owner->view()->theLockingInset() &&
+                   owner->view()->theLockingInset()->getLyXText(owner->view()))
+                   font = owner->view()->theLockingInset()->
+                       getLyXText(owner->view())->real_current_font;
+               else
+                   font = owner->view()->text->real_current_font;
                switch (action) {
                case LFUN_EMPH:
                        if (font.emph() == LyXFont::ON)
@@ -437,21 +453,26 @@ LyXFunc::func_status LyXFunc::getStatus(int ac) const
 }
 
 
-string LyXFunc::Dispatch(string const & s) 
+string const LyXFunc::Dispatch(string const & s) 
 {
        // Split command string into command and argument
-       string cmd, line = frontStrip(s);
+       string cmd;
+       string line = frontStrip(s);
        string arg = strip(frontStrip(split(line, cmd, ' ')));
 
-       return Dispatch(lyxaction.LookupFunc(cmd.c_str()), arg.c_str());
+       return Dispatch(lyxaction.LookupFunc(cmd), arg);
 }
 
 
-string LyXFunc::Dispatch(int ac,
-                        char const * do_not_use_this_arg)
+string const LyXFunc::Dispatch(int ac,
+                        string const & do_not_use_this_arg)
 {
+       lyxerr[Debug::ACTION] << "LyXFunc::Dispatch: action[" << ac
+                             <<"] arg[" << do_not_use_this_arg << "]" << endl;
+       
        string argument;
        kb_action action;
+       LyXText * text = 0;
         
         // we have not done anything wrong yet.
         errorstat = false;
@@ -466,7 +487,7 @@ string LyXFunc::Dispatch(int ac,
                        argument = tmparg;
        } else {
                action = static_cast<kb_action>(ac);
-               if (do_not_use_this_arg)
+               if (!do_not_use_this_arg.empty())
                        argument = do_not_use_this_arg; // except here
        }
     
@@ -476,7 +497,7 @@ string LyXFunc::Dispatch(int ac,
                owner->view()->hideCursor();
 
        // We cannot use this function here
-       if (getStatus(action) & Disabled)
+       if (getStatus(ac) & Disabled)
                goto exit_with_message;
 
        commandshortcut.erase();
@@ -495,7 +516,7 @@ string LyXFunc::Dispatch(int ac,
                                // this is better
                                pseudoaction = 
                                        lyxaction.searchActionArg(action,
-                                                                 argument.c_str());
+                                                                 argument);
 
                                if (pseudoaction == -1) {
                                        pseudoaction = action;
@@ -527,10 +548,7 @@ string LyXFunc::Dispatch(int ac,
                }
         }
 
-       // If in math mode pass the control to
-       // the math inset [asierra060396]
-       if (owner->view()->available() &&
-           owner->view()->the_locking_inset) {
+       if (owner->view()->available() && owner->view()->theLockingInset()) {
                UpdatableInset::RESULT result;
                if ((action > 1) || ((action == LFUN_UNKNOWN_ACTION) &&
                                     (keyseq.length >= -1)))
@@ -540,9 +558,10 @@ string LyXFunc::Dispatch(int ac,
                        }
                        // Undo/Redo pre 0.13 is a bit tricky for insets.
                        if (action == LFUN_UNDO) {
-                               int slx, sly;
+                               int slx;
+                               int sly;
                                UpdatableInset * inset = 
-                                       owner->view()->the_locking_inset;
+                                       owner->view()->theLockingInset();
                                inset->GetCursorPos(owner->view(), slx, sly);
                                owner->view()->unlockInset(inset);
                                owner->view()->menuUndo();
@@ -559,9 +578,10 @@ string LyXFunc::Dispatch(int ac,
                                        inset->Edit(owner->view(),slx,sly,0);
                                return string();
                        } else if (action == LFUN_REDO) {
-                               int slx, sly;
+                               int slx;
+                               int sly;
                                UpdatableInset * inset = owner->view()->
-                                       the_locking_inset;
+                                       theLockingInset();
                                inset->GetCursorPos(owner->view(), slx, sly);
                                owner->view()->unlockInset(inset);
                                owner->view()->menuRedo();
@@ -572,7 +592,7 @@ string LyXFunc::Dispatch(int ac,
                                if (inset)
                                        inset->Edit(owner->view(),slx,sly,0); 
                                return string();
-                       } else if (((result=owner->view()->the_locking_inset->
+                       } else if (((result=owner->view()->theLockingInset()->
                                   LocalDispatch(owner->view(), action,
                                                 argument)) ==
                                   UpdatableInset::DISPATCHED) ||
@@ -580,44 +600,47 @@ string LyXFunc::Dispatch(int ac,
                                return string();
                        else {
                                setMessage(N_("Text mode"));
-                               switch(action) {
+                               switch (action) {
                                case LFUN_UNKNOWN_ACTION:
                                case LFUN_BREAKPARAGRAPH:
                                case LFUN_BREAKLINE:
                                        owner->view()->text->CursorRight(owner->view());
                                        owner->view()->setState();
-                                       owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+                                       owner->showState();
                                        break;
                                case LFUN_RIGHT:
                                        if (!owner->view()->text->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
                                                owner->view()->text->CursorRight(owner->view());
                                                moveCursorUpdate(false);
-                                               owner->getMiniBuffer()->
-                                                       Set(CurrentState(owner->view()));
+                                               owner->showState();
                                        }
                                        return string();
                                case LFUN_LEFT: 
                                        if (owner->view()->text->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
                                                owner->view()->text->CursorRight(owner->view());
                                                moveCursorUpdate(false);
-                                               owner->getMiniBuffer()->
-                                                       Set(CurrentState(owner->view()));
+                                               owner->showState();
                                        }
                                        return string();
                                case LFUN_DOWN:
                                        owner->view()->text->CursorDown(owner->view());
                                        moveCursorUpdate(false);
-                                       owner->getMiniBuffer()->
-                                               Set(CurrentState(owner->view()));
+                                       owner->showState();
                                        return string();
                                default:
                                        break;
                                }
                        }
                }
+               if (owner->view()->theLockingInset())
+                       text = owner->view()->theLockingInset()->
+                               getLyXText(owner->view());
        }
 
-       switch(action) {
+       if (!text)
+           text = owner->view()->text;
+
+       switch (action) {
                // --- Misc -------------------------------------------
        case LFUN_WORDFINDFORWARD  : 
        case LFUN_WORDFINDBACKWARD : {
@@ -635,8 +658,8 @@ string LyXFunc::Dispatch(int ac,
 
                if (!searched_string.empty() &&
                    ((action == LFUN_WORDFINDBACKWARD) ? 
-                    ltCur->SearchBackward(owner->view(), searched_string.c_str()) :
-                    ltCur->SearchForward(owner->view(), searched_string.c_str()))) {
+                    ltCur->SearchBackward(owner->view(), searched_string) :
+                    ltCur->SearchForward(owner->view(), searched_string))) {
 
                        // ??? What is that ???
                        owner->view()->update(BufferView::SELECT|BufferView::FITCUR);
@@ -647,7 +670,7 @@ string LyXFunc::Dispatch(int ac,
                        owner->view()->text->ClearSelection();
 
                        // Move cursor so that successive C-s 's will not stand in place. 
-                       ifaction == LFUN_WORDFINDFORWARD ) 
+                       if (action == LFUN_WORDFINDFORWARD ) 
                                owner->view()->text->CursorRightOneWord(owner->view());
                        owner->view()->text->FinishUndo();
                        moveCursorUpdate(false);
@@ -677,15 +700,15 @@ string LyXFunc::Dispatch(int ac,
 
        // --- Misc -------------------------------------------
        case LFUN_EXEC_COMMAND:
-               owner->getMiniBuffer()->ExecCommand(); 
+               owner->getMiniBuffer()->PrepareForCommand(); 
                break;
                
        case LFUN_CANCEL:                   // RVDK_PATCH_5
                keyseq.reset();
                meta_fake_bit = 0;
-               if(owner->view()->available())
+               if (owner->view()->available())
                        // cancel any selection
-                       Dispatch(LFUN_MARK_OFF, 0);
+                       Dispatch(LFUN_MARK_OFF);
                setMessage(N_("Cancel"));
                break;
 
@@ -694,7 +717,6 @@ string LyXFunc::Dispatch(int ac,
                meta_fake_bit = Mod1Mask;
                string buf;
                keyseq.print(buf, true);
-               string res = string("M-") + buf;
                setMessage(buf); // RVDK_PATCH_5
        }
        break;  
@@ -737,60 +759,58 @@ string LyXFunc::Dispatch(int ac,
                break;
                
        case LFUN_MENUWRITE:
-               owner->getMiniBuffer()->Set(_("Saving document"),
-                                           MakeDisplayPath(owner->buffer()->fileName()),
-                                           "...");
-               MenuWrite(owner->buffer());
-               //owner->getMiniBuffer()-> {
-               //      Set(_("Document saved as"),
-               //          MakeDisplayPath(owner->buffer()->fileName()));
-               //} else {
-               //owner->getMiniBuffer()->Set(_("Save failed!"));
-               //}
+               if (!owner->buffer()->isUnnamed()) {
+                       owner->getMiniBuffer()->Set(_("Saving document"),
+                                                   MakeDisplayPath(owner->buffer()->fileName()),
+                                                   "...");
+                       MenuWrite(owner->view(), owner->buffer());
+                       //owner->getMiniBuffer()-> {
+                       //      Set(_("Document saved as"),
+                       //          MakeDisplayPath(owner->buffer()->fileName()));
+                       //} else {
+                       //owner->getMiniBuffer()->Set(_("Save failed!"));
+                       //}
+               } else {
+                       MenuWriteAs(owner->view(), owner->buffer());
+               }
                break;
                
        case LFUN_MENUWRITEAS:
-               MenuWriteAs(owner->buffer());
+               MenuWriteAs(owner->view(), owner->buffer());
                break;
                
        case LFUN_MENURELOAD:
                reloadBuffer();
                break;
                
-       case LFUN_PREVIEW:
-               PreviewDVI(owner->buffer());
+       case LFUN_UPDATE:
+               Exporter::Export(owner->buffer(), argument, true);
                break;
-                       
-       case LFUN_PREVIEWPS:
-               PreviewPostscript(owner->buffer());
-               break;
-               
-       case LFUN_RUNLATEX:
-               MenuRunLaTeX(owner->buffer());
+
+       case LFUN_PREVIEW:
+               Exporter::Preview(owner->buffer(), argument);
                break;
                
         case LFUN_BUILDPROG:
-                MenuBuildProg(owner->buffer());
+               Exporter::Export(owner->buffer(), "program", true);
                 break;
                 
        case LFUN_RUNCHKTEX:
                MenuRunChktex(owner->buffer());
                break;
-               
-       case LFUN_RUNDVIPS:
-               CreatePostscript(owner->buffer(), false);
-               break;
-               
+                               
        case LFUN_MENUPRINT:
                owner->getDialogs()->showPrint();
                break;
 
+#if 0
        case LFUN_FAX:
                MenuFax(owner->buffer());
                break;
-                       
+#endif
+               
        case LFUN_EXPORT:
-               MenuExport(owner->buffer(), argument);
+               Exporter::Export(owner->buffer(), argument, false);
                break;
 
        case LFUN_IMPORT:
@@ -806,76 +826,68 @@ string LyXFunc::Dispatch(int ac,
        case LFUN_LOTVIEW:
        case LFUN_LOAVIEW:
        {
-               Buffer::TocType type = Buffer::TOC_TOC;
-               if (action == LFUN_LOFVIEW)
-                       type = Buffer::TOC_LOF;
-               else if (action == LFUN_LOTVIEW)
-                       type = Buffer::TOC_LOT;
-               else if (action == LFUN_LOAVIEW)
-                       type = Buffer::TOC_LOA;
-               fl_set_choice(fd_form_toc->toctype,type + 1);
-               TocUpdateCB(0, 0);
-               if (fd_form_toc->form_toc->visible) {
-                       fl_raise_form(fd_form_toc->form_toc);
-               } else {
-                       static int ow = -1, oh;
-                       fl_show_form(fd_form_toc->form_toc,
-                                    FL_PLACE_MOUSE |
-                                    FL_FREE_SIZE, FL_FULLBORDER,
-                                    _("Table of Contents"));
-                       if (ow < 0) {
-                               ow = fd_form_toc->form_toc->w;
-                               oh = fd_form_toc->form_toc->h;
-                       }
-                       fl_set_form_minsize(fd_form_toc->form_toc, ow, oh);
-               }
+               InsetCommandParams p;
+               
+               if (action == LFUN_TOCVIEW )
+                       p.setCmdName( "tableofcontents" );
+               else if (action == LFUN_LOAVIEW )
+                       p.setCmdName( "listofalgorithms" );
+               else if (action == LFUN_LOFVIEW )
+                       p.setCmdName( "listoffigures" );
+               else
+                       p.setCmdName( "listoftables" );
+
+               owner->getDialogs()->createTOC( p.getAsString() );
                break;
        }       
+
        case LFUN_TOC_INSERT:
-       {
-               Inset * new_inset = new InsetTOC(owner->buffer());
-               if (!owner->view()->insertInset(new_inset, "Standard", true))
-                       delete new_inset;
-               break;
-       }
-       
-       case LFUN_LOF_INSERT:
-       {
-               Inset * new_inset = new InsetLOF(owner->buffer());
-               if (!owner->view()->insertInset(new_inset, "Standard", true))
-                       delete new_inset;
-               break;
-       }
-       
        case LFUN_LOA_INSERT:
-       {
-               Inset * new_inset = new InsetLOA(owner->buffer());
-               if (!owner->view()->insertInset(new_inset, "Standard", true))
-                       delete new_inset;
-               break;
-       }
-
+       case LFUN_LOF_INSERT:
        case LFUN_LOT_INSERT:
        {
-               Inset * new_inset = new InsetLOT(owner->buffer());
-               if (!owner->view()->insertInset(new_inset, "Standard", true))
-                       delete new_inset;
+               InsetCommandParams p;
+               
+               if (action == LFUN_TOC_INSERT )
+                       p.setCmdName( "tableofcontents" );
+               else if (action == LFUN_LOA_INSERT )
+                       p.setCmdName( "listofalgorithms" );
+               else if (action == LFUN_LOF_INSERT )
+                       p.setCmdName( "listoffigures" );
+               else
+                       p.setCmdName( "listoftables" );
+
+               Inset * inset = new InsetTOC( p );
+               if (!owner->view()->insertInset( inset, "Standard", true ) )
+                       delete inset;
                break;
        }
                
-       case LFUN_TABLE:
-               Table();
+       case LFUN_DIALOG_TABULAR_INSERT:
+               owner->getDialogs()->showTabularCreate();
                break;
                
+       case LFUN_TABULAR_FEATURE:
+       case LFUN_SCROLL_INSET:
+               // this is not handled here as this funktion is only aktive
+               // if we have a locking_inset and that one is (or contains)
+               // a tabular-inset
+               break;
+
        case LFUN_FIGURE:
                Figure();
                break;
 
-       case LFUN_INSERT_GRAPHICS:
+       case LFUN_INSET_GRAPHICS:
        {
                Inset * new_inset = new InsetGraphics;
-               if (!owner->view()->insertInset(new_inset))
+               if (!owner->view()->insertInset(new_inset)) {
                        delete new_inset;
+               } else {
+                       // this is need because you don't use a inset->Edit()
+                       owner->view()->updateInset(new_inset, true);
+                       new_inset->Edit(owner->view(), 0, 0, 0);
+               }
                break;
        }
        
@@ -938,18 +950,19 @@ string LyXFunc::Dispatch(int ac,
        case LFUN_REMOVEERRORS:
                if (owner->view()->removeAutoInsets()) {
                        owner->view()->redraw();
-                       owner->view()->fitCursor();
-                       //owner->view()->updateScrollbar();
+                       owner->view()->fitCursor(owner->view()->text);
                }
                break;
                
        case LFUN_GOTONOTE:
                owner->view()->gotoNote();
                break;
-               
+
+#ifndef NEW_INSETS
        case LFUN_OPENSTUFF:
                owner->view()->openStuff();
                break;
+#endif
                
        case LFUN_HYPHENATION:
                owner->view()->hyphenationPoint();
@@ -986,30 +999,30 @@ string LyXFunc::Dispatch(int ac,
        case LFUN_FREE:
                Free(owner->view());
                owner->view()->setState();
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
                
        case LFUN_TEX:
                Tex(owner->view());
                owner->view()->setState();
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
-               
+#ifndef NEW_INSETS             
        case LFUN_MELT:
                Melt(owner->view());
                break;
-               
+#endif
        case LFUN_RECONFIGURE:
                Reconfigure(owner->view());
                break;
-
+#ifndef NEW_INSETS
        case LFUN_FOOTMELT:
                if (owner->view()->available()
                    && !owner->view()->text->selection
                    && owner->view()->text->cursor.par()->footnoteflag
                    != LyXParagraph::NO_FOOTNOTE)
                        { // only melt footnotes with FOOTMELT, not margins etc
-                               if(owner->view()->text->cursor.par()->footnotekind == LyXParagraph::FOOTNOTE)
+                               if (owner->view()->text->cursor.par()->footnotekind == LyXParagraph::FOOTNOTE)
                                        Melt(owner->view());
                        }
                else
@@ -1023,17 +1036,71 @@ string LyXFunc::Dispatch(int ac,
                    && owner->view()->text->cursor.par()->footnoteflag
                    != LyXParagraph::NO_FOOTNOTE) {
                        // only melt margins
-                       if(owner->view()->text->cursor.par()->footnotekind == LyXParagraph::MARGIN)
+                       if (owner->view()->text->cursor.par()->footnotekind == LyXParagraph::MARGIN)
                                Melt(owner->view());
                } else
                        Margin(owner->view()); 
                owner->view()->setState();
                break;
-               
+#endif
+#ifndef NEW_INSETS
+       case LFUN_FLOATSOPERATE:
+               if (argument == "openfoot")
+                       owner->view()->allFloats(1,0);
+               else if (argument == "closefoot")
+                       owner->view()->allFloats(0,0);
+               else if (argument == "openfig")
+                       owner->view()->allFloats(1,1);
+               else if (argument == "closefig")
+                       owner->view()->allFloats(0,1);
+               break;
+#else
+#warning Find another implementation here (or another lyxfunc)!
+#endif
        case LFUN_HELP_COPYRIGHT:
                owner->getDialogs()->showCopyright();
                break;
 
+       case LFUN_HELP_CREDITS:
+               owner->getDialogs()->showCredits();
+               break;
+
+        case LFUN_HELP_OPEN: {
+               string arg = argument;
+               if (arg.empty()) {
+                       setErrorMessage(N_("Missing argument"));
+                       break;
+               }
+               ProhibitInput(owner->view());
+               string fname = i18nLibFileSearch("doc", arg, "lyx");
+               if (fname.empty()) {
+                       lyxerr << "LyX: unable to find documentation file `"
+                              << arg << "'. Bad installation?" << endl;
+                       AllowInput(owner->view());
+                       break;
+               }
+               owner->getMiniBuffer()->Set(_("Opening help file"),
+                                           MakeDisplayPath(fname),"...");
+               owner->view()->buffer(bufferlist.loadLyXFile(fname,false));
+               AllowInput(owner->view());
+               break;
+        }
+
+       case LFUN_HELP_VERSION: {
+               ProhibitInput(owner->view());
+               string msg(_("LyX Version "));
+               msg += LYX_VERSION;
+               msg += " of ";
+               msg += LYX_RELEASE;
+               fl_show_message(msg.c_str(),
+                               (_("Library directory: ")
+                                + MakeDisplayPath(system_lyxdir)).c_str(),
+                               (_("User directory: ") 
+                                + MakeDisplayPath(user_lyxdir)).c_str());
+               AllowInput(owner->view());
+               break;
+       }
+       
                // --- version control -------------------------------
        case LFUN_VC_REGISTER:
        {
@@ -1078,6 +1145,11 @@ string LyXFunc::Dispatch(int ac,
        
        // --- buffers ----------------------------------------
 
+        case LFUN_SWITCHBUFFER:
+                owner->view()->buffer(bufferlist.getBuffer(argument));
+               break;
+
+
        case LFUN_FILE_INSERT:
        {
                MenuInsertLyXFile(argument);
@@ -1124,7 +1196,7 @@ string LyXFunc::Dispatch(int ac,
                Dispatch(int(LFUN_LAYOUT), 
                         textclasslist.NameOfLayout(owner->view()
                                                    ->buffer()->params.textclass,
-                                                   sel).c_str());
+                                                   sel));
                return string();
        }
                
@@ -1162,10 +1234,7 @@ string LyXFunc::Dispatch(int ac,
                        owner->view()->update(BufferView::SELECT|BufferView::FITCUR);
                        owner->view()->text->
                                SetLayout(owner->view(), layout.second);
-                       owner->getToolbar()->combox->
-                               select(owner->view()->
-                                      text->cursor.par()->
-                                      GetLayout() + 1);
+                       owner->setLayout(layout.second);
                        owner->view()->update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
                        owner->view()->setState();
                }
@@ -1173,94 +1242,97 @@ string LyXFunc::Dispatch(int ac,
        break;
 
        case LFUN_LAYOUT_DOCUMENT:
-               MenuLayoutDocument();
+               owner->getDialogs()->showLayoutDocument();
                break;
                
        case LFUN_LAYOUT_PARAGRAPH:
+#ifdef USE_OLD_PARAGRAPH_LAYOUT
                MenuLayoutParagraph();
+#else
+               owner->getDialogs()->showLayoutParagraph();
+#endif
                break;
                
        case LFUN_LAYOUT_CHARACTER:
                MenuLayoutCharacter();
                break;
-               
-       case LFUN_LAYOUT_TABLE:
-       {
-               int flag = 0;
-               if (argument == "true") flag = 1;
-               MenuLayoutTable(flag);
-       }
-       break;
-               
-       case LFUN_LAYOUT_PAPER:
-               MenuLayoutPaper();
-               break;
-               
-       case LFUN_LAYOUT_QUOTES:
-               MenuLayoutQuotes();
-               break;
-               
+
+       case LFUN_LAYOUT_TABULAR:
+           if (owner->view()->theLockingInset()) {
+               if (owner->view()->theLockingInset()->LyxCode()==Inset::TABULAR_CODE) {
+                   InsetTabular * inset = static_cast<InsetTabular *>
+                       (owner->view()->theLockingInset());
+                   inset->OpenLayoutDialog(owner->view());
+               } else if (owner->view()->theLockingInset()->
+                          GetFirstLockingInsetOfType(Inset::TABULAR_CODE)!=0) {
+                   InsetTabular * inset = static_cast<InsetTabular *>(
+                       owner->view()->theLockingInset()->GetFirstLockingInsetOfType(Inset::TABULAR_CODE));
+                   inset->OpenLayoutDialog(owner->view());
+               }
+           }
+           break;
+
        case LFUN_LAYOUT_PREAMBLE:
                MenuLayoutPreamble();
                break;
                
        case LFUN_LAYOUT_SAVE_DEFAULT:
-               MenuLayoutSave();
+               MenuLayoutSave(owner->view());
                break;
                
        case LFUN_DROP_LAYOUTS_CHOICE:
-               owner->getToolbar()->combox->Show();
+               owner->getToolbar()->openLayoutList();
                break;
 
        case LFUN_LANGUAGE:
                Lang(owner->view(), argument);
                owner->view()->setState();
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
 
        case LFUN_EMPH:
                Emph(owner->view());
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
 
        case LFUN_BOLD:
                Bold(owner->view());
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
                
        case LFUN_NOUN:
                Noun(owner->view());
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
                
        case LFUN_CODE:
                Code(owner->view());
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
                
        case LFUN_SANS:
                Sans(owner->view());
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
                
        case LFUN_ROMAN:
                Roman(owner->view());
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
                
        case LFUN_DEFAULT:
                StyleReset(owner->view());
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
                
        case LFUN_UNDERLINE:
                Underline(owner->view());
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
                
        case LFUN_FONT_SIZE:
                FontSize(owner->view(), argument);
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
                
        case LFUN_FONT_STATE:
@@ -1269,53 +1341,56 @@ string LyXFunc::Dispatch(int ac,
                
        case LFUN_UPCASE_WORD:
                owner->view()->update(BufferView::SELECT|BufferView::FITCUR);
-               owner->view()->text->ChangeWordCase(owner->view(),
-                                                   LyXText::text_uppercase);
+               text->ChangeWordCase(owner->view(), LyXText::text_uppercase);
+               if (text->inset_owner)
+                   owner->view()->updateInset(text->inset_owner, true);
                owner->view()->update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
                break;
                
        case LFUN_LOWCASE_WORD:
                owner->view()->update(BufferView::SELECT|BufferView::FITCUR);
-               owner->view()->text->ChangeWordCase(owner->view(),
-                                                   LyXText::text_lowercase);
+               text->ChangeWordCase(owner->view(), LyXText::text_lowercase);
+               if (text->inset_owner)
+                   owner->view()->updateInset(text->inset_owner, true);
                owner->view()->update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
                break;
                
        case LFUN_CAPITALIZE_WORD:
                owner->view()->update(BufferView::SELECT|BufferView::FITCUR);
-               owner->view()->text->ChangeWordCase(owner->view(),
-                                                   LyXText::text_capitalization);
+               text->ChangeWordCase(owner->view(),
+                                    LyXText::text_capitalization);
+               if (text->inset_owner)
+                   owner->view()->updateInset(text->inset_owner, true);
                owner->view()->update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
                break;
                
        case LFUN_INSERT_LABEL:
-               MenuInsertLabel(argument.c_str());
-               break;
-               
-       case LFUN_INSERT_REF:
-               MenuInsertRef();
+               MenuInsertLabel(owner->view(), argument);
                break;
                
-       case LFUN_REFTOGGLE:
-       {
-               InsetRef * inset = 
-                       static_cast<InsetRef*>(getInsetByCode(Inset::REF_CODE));
-               if (inset) {
-                       inset->Toggle();
-                       owner->view()->updateInset(inset, true);
+       case LFUN_REF_INSERT:
+               if (argument.empty()) {
+                       InsetCommandParams p("ref");
+               owner->getDialogs()->createRef(p.getAsString());
                } else {
-                       setErrorMessage(N_("No cross-reference to toggle"));
+                       InsetCommandParams p;
+                       p.setFromString(argument);
+
+                       InsetRef * inset = new InsetRef(p, *owner->buffer());
+                       if (!owner->view()->insertInset(inset))
+                               delete inset;
+                       else
+                               owner->view()->updateInset(inset, true);
                }
-       }
-       break;
-       
-       case LFUN_REFBACK:
+               break;
+
+       case LFUN_REF_BACK:
        {
                owner->view()->restorePosition();
        }
        break;
 
-       case LFUN_REFGOTO:
+       case LFUN_REF_GOTO:
        {
                string label(argument);
                if (label.empty()) {
@@ -1336,7 +1411,7 @@ string LyXFunc::Dispatch(int ac,
        break;
                
        case LFUN_MENU_OPEN_BY_NAME:
-               owner->getMenus()->openByName(argument);
+               owner->getMenubar()->openByName(argument);
                break; // RVDK_PATCH_5
                
        case LFUN_SPELLCHECK:
@@ -1349,7 +1424,7 @@ string LyXFunc::Dispatch(int ac,
        {
                LyXText * tmptext = owner->view()->text;
                bool is_rtl = tmptext->cursor.par()->isRightToLeftPar(owner->buffer()->params);
-               if(!tmptext->mark_set)
+               if (!tmptext->mark_set)
                        owner->view()->beforeChange();
                owner->view()->update(BufferView::SELECT|BufferView::FITCUR);
                if (is_rtl)
@@ -1368,7 +1443,7 @@ string LyXFunc::Dispatch(int ac,
                        tmptext->CursorRight(owner->view(), false);
                owner->view()->text->FinishUndo();
                moveCursorUpdate(false);
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
        }
        break;
                
@@ -1378,23 +1453,28 @@ string LyXFunc::Dispatch(int ac,
                // it simpler? (Lgb)
                LyXText * txt = owner->view()->text;
                bool is_rtl = txt->cursor.par()->isRightToLeftPar(owner->buffer()->params);
-               if(!txt->mark_set) owner->view()->beforeChange();
+               if (!txt->mark_set) owner->view()->beforeChange();
                owner->view()->update(BufferView::SELECT|BufferView::FITCUR);
+               LyXCursor cur = txt->cursor;
                if (!is_rtl)
                        txt->CursorLeft(owner->view(), false);
-               if (txt->cursor.pos() < txt->cursor.par()->Last()
-                   && txt->cursor.par()->GetChar(txt->cursor.pos())
-                   == LyXParagraph::META_INSET
-                   && txt->cursor.par()->GetInset(txt->cursor.pos())
-                   && txt->cursor.par()->GetInset(txt->cursor.pos())->Editable() == Inset::HIGHLY_EDITABLE) {
+               if ((cur != txt->cursor) && // only if really moved!
+                   txt->cursor.pos() < txt->cursor.par()->Last() &&
+                   (txt->cursor.par()->GetChar(txt->cursor.pos()) ==
+                    LyXParagraph::META_INSET) &&
+                   txt->cursor.par()->GetInset(txt->cursor.pos()) &&
+                   (txt->cursor.par()->GetInset(txt->cursor.pos())->Editable()
+                    == Inset::HIGHLY_EDITABLE))
+               {
                        Inset * tmpinset = txt->cursor.par()->GetInset(txt->cursor.pos());
                        setMessage(tmpinset->EditMessage());
                        LyXFont font = txt->GetFont(owner->view()->buffer(),
                                                    txt->cursor.par(),
                                                    txt->cursor.pos());
                        tmpinset->Edit(owner->view(),
-                                      tmpinset->x() + tmpinset->width(owner->view()->painter(),font),
-                                      tmpinset->descent(owner->view()->painter(),font),
+                                      tmpinset->x() +
+                                      tmpinset->width(owner->view(),font),
+                                      tmpinset->descent(owner->view(),font),
                                       0);
                        break;
                }
@@ -1403,144 +1483,154 @@ string LyXFunc::Dispatch(int ac,
 
                owner->view()->text->FinishUndo();
                moveCursorUpdate(false);
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
        }
        break;
                
        case LFUN_UP:
-               if(!owner->view()->text->mark_set) owner->view()->beforeChange();
+               if (!owner->view()->text->mark_set) owner->view()->beforeChange();
                owner->view()->update(BufferView::UPDATE);
                owner->view()->text->CursorUp(owner->view());
                owner->view()->text->FinishUndo();
                moveCursorUpdate(false);
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
                
        case LFUN_DOWN:
-               if(!owner->view()->text->mark_set)
+               if (!owner->view()->text->mark_set)
                        owner->view()->beforeChange();
                owner->view()->update(BufferView::UPDATE);
                owner->view()->text->CursorDown(owner->view());
                owner->view()->text->FinishUndo();
                moveCursorUpdate(false);
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
 
        case LFUN_UP_PARAGRAPH:
-               if(!owner->view()->text->mark_set)
+               if (!owner->view()->text->mark_set)
                        owner->view()->beforeChange();
                owner->view()->update(BufferView::UPDATE);
                owner->view()->text->CursorUpParagraph(owner->view());
                owner->view()->text->FinishUndo();
                moveCursorUpdate(false);
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
                
        case LFUN_DOWN_PARAGRAPH:
-               if(!owner->view()->text->mark_set)
+               if (!owner->view()->text->mark_set)
                        owner->view()->beforeChange();
                owner->view()->update(BufferView::UPDATE);
                owner->view()->text->CursorDownParagraph(owner->view());
                owner->view()->text->FinishUndo();
                moveCursorUpdate(false);
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
                
        case LFUN_PRIOR:
-               if(!owner->view()->text->mark_set)
-                       owner->view()->beforeChange();
+               if (!text->mark_set)
+                   owner->view()->beforeChange();
                owner->view()->update(BufferView::UPDATE);
-               owner->view()->cursorPrevious();
+               owner->view()->cursorPrevious(text);
                owner->view()->text->FinishUndo();
-               moveCursorUpdate(false);
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               if (text->inset_owner)
+                   owner->view()->updateInset(text->inset_owner, false);
+               else
+                   moveCursorUpdate(false);
+               owner->showState();
                break;
                
        case LFUN_NEXT:
-               if(!owner->view()->text->mark_set)
+               if (!text->mark_set)
                        owner->view()->beforeChange();
                owner->view()->update(BufferView::UPDATE);
-               owner->view()->cursorNext();
+               owner->view()->cursorNext(text);
                owner->view()->text->FinishUndo();
-               moveCursorUpdate(false);
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               if (text->inset_owner)
+                   owner->view()->updateInset(text->inset_owner, false);
+               else
+                   moveCursorUpdate(false);
+               owner->showState();
                break;
                
        case LFUN_HOME:
-               if(!owner->view()->text->mark_set)
+               if (!owner->view()->text->mark_set)
                        owner->view()->beforeChange();
                owner->view()->update(BufferView::SELECT|BufferView::FITCUR);
                owner->view()->text->CursorHome(owner->view());
                owner->view()->text->FinishUndo();
                moveCursorUpdate(false);
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
                
        case LFUN_END:
-               if(!owner->view()->text->mark_set)
+               if (!owner->view()->text->mark_set)
                        owner->view()->beforeChange();
                owner->view()->update(BufferView::SELECT|BufferView::FITCUR);
                owner->view()->text->CursorEnd(owner->view());
                owner->view()->text->FinishUndo();
                moveCursorUpdate(false);
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
                
        case LFUN_SHIFT_TAB:
        case LFUN_TAB:
-               if(!owner->view()->text->mark_set)
+               if (!owner->view()->text->mark_set)
                        owner->view()->beforeChange();
                owner->view()->update(BufferView::SELECT|BufferView::FITCUR);
                owner->view()->text->CursorTab(owner->view());
                owner->view()->text->FinishUndo();
                moveCursorUpdate(false);
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
                
        case LFUN_WORDRIGHT:
-               if(!owner->view()->text->mark_set)
+               if (!text->mark_set)
                        owner->view()->beforeChange();
                owner->view()->update(BufferView::SELECT|BufferView::FITCUR);
-               if (owner->view()->text->cursor.par()->isRightToLeftPar(owner->buffer()->params))
-                       owner->view()->text->CursorLeftOneWord(owner->view());
+               if (text->cursor.par()->isRightToLeftPar(owner->buffer()->params))
+                       text->CursorLeftOneWord(owner->view());
                else
-                       owner->view()->text->CursorRightOneWord(owner->view());
+                       text->CursorRightOneWord(owner->view());
                owner->view()->text->FinishUndo();
+               if (text->inset_owner)
+                   owner->view()->updateInset(text->inset_owner, true);
                moveCursorUpdate(false);
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
                
        case LFUN_WORDLEFT:
-               if(!owner->view()->text->mark_set)
+               if (!text->mark_set)
                        owner->view()->beforeChange();
                owner->view()->update(BufferView::SELECT|BufferView::FITCUR);
-               if (owner->view()->text->cursor.par()->isRightToLeftPar(owner->buffer()->params))
-                       owner->view()->text->CursorRightOneWord(owner->view());
+               if (text->cursor.par()->isRightToLeftPar(owner->buffer()->params))
+                       text->CursorRightOneWord(owner->view());
                else
-                       owner->view()->text->CursorLeftOneWord(owner->view());
+                       text->CursorLeftOneWord(owner->view());
                owner->view()->text->FinishUndo();
+               if (text->inset_owner)
+                   owner->view()->updateInset(text->inset_owner, true);
                moveCursorUpdate(false);
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
                
        case LFUN_BEGINNINGBUF:
-               if(!owner->view()->text->mark_set)
+               if (!owner->view()->text->mark_set)
                        owner->view()->beforeChange();
                owner->view()->update(BufferView::SELECT|BufferView::FITCUR);
                owner->view()->text->CursorTop(owner->view());
                owner->view()->text->FinishUndo();
                moveCursorUpdate(false);
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
                
        case LFUN_ENDBUF:
-               if(!owner->view()->text->mark_set)
+               if (!owner->view()->text->mark_set)
                        owner->view()->beforeChange();
                owner->view()->update(BufferView::SELECT|BufferView::FITCUR);
                owner->view()->text->CursorBottom(owner->view());
                owner->view()->text->FinishUndo();
                moveCursorUpdate(false);
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
 
       
@@ -1553,7 +1643,7 @@ string LyXFunc::Dispatch(int ac,
                        owner->view()->text->CursorRight(owner->view());
                owner->view()->text->FinishUndo();
                moveCursorUpdate(true);
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
                
        case LFUN_LEFTSEL:
@@ -1564,7 +1654,7 @@ string LyXFunc::Dispatch(int ac,
                        owner->view()->text->CursorLeft(owner->view());
                owner->view()->text->FinishUndo();
                moveCursorUpdate(true);
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
                
        case LFUN_UPSEL:
@@ -1572,7 +1662,7 @@ string LyXFunc::Dispatch(int ac,
                owner->view()->text->CursorUp(owner->view());
                owner->view()->text->FinishUndo();
                moveCursorUpdate(true);
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
                
        case LFUN_DOWNSEL:
@@ -1580,7 +1670,7 @@ string LyXFunc::Dispatch(int ac,
                owner->view()->text->CursorDown(owner->view());
                owner->view()->text->FinishUndo();
                moveCursorUpdate(true);
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
 
        case LFUN_UP_PARAGRAPHSEL:
@@ -1588,7 +1678,7 @@ string LyXFunc::Dispatch(int ac,
                owner->view()->text->CursorUpParagraph(owner->view());
                owner->view()->text->FinishUndo();
                moveCursorUpdate(true);
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
                
        case LFUN_DOWN_PARAGRAPHSEL:
@@ -1596,23 +1686,29 @@ string LyXFunc::Dispatch(int ac,
                owner->view()->text->CursorDownParagraph(owner->view());
                owner->view()->text->FinishUndo();
                moveCursorUpdate(true);
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
                
        case LFUN_PRIORSEL:
                owner->view()->update(BufferView::SELECT|BufferView::FITCUR);
-               owner->view()->cursorPrevious();
+               owner->view()->cursorPrevious(text);
                owner->view()->text->FinishUndo();
-               moveCursorUpdate(true);
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               if (text->inset_owner)
+                   owner->view()->updateInset(text->inset_owner, false);
+               else
+                   moveCursorUpdate(true);
+               owner->showState();
                break;
                
        case LFUN_NEXTSEL:
                owner->view()->update(BufferView::SELECT|BufferView::FITCUR);
-               owner->view()->cursorNext();
+               owner->view()->cursorNext(text);
                owner->view()->text->FinishUndo();
-               moveCursorUpdate(true);
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               if (text->inset_owner)
+                   owner->view()->updateInset(text->inset_owner, false);
+               else
+                   moveCursorUpdate(true);
+               owner->showState();
                break;
                
        case LFUN_HOMESEL:
@@ -1620,7 +1716,7 @@ string LyXFunc::Dispatch(int ac,
                owner->view()->text->CursorHome(owner->view());
                owner->view()->text->FinishUndo();
                moveCursorUpdate(true);
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
                
        case LFUN_ENDSEL:
@@ -1628,7 +1724,7 @@ string LyXFunc::Dispatch(int ac,
                owner->view()->text->CursorEnd(owner->view());
                owner->view()->text->FinishUndo();
                moveCursorUpdate(true);
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
                
        case LFUN_WORDRIGHTSEL:
@@ -1639,7 +1735,7 @@ string LyXFunc::Dispatch(int ac,
                        owner->view()->text->CursorRightOneWord(owner->view());
                owner->view()->text->FinishUndo();
                moveCursorUpdate(true);
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
                
        case LFUN_WORDLEFTSEL:
@@ -1650,7 +1746,7 @@ string LyXFunc::Dispatch(int ac,
                        owner->view()->text->CursorLeftOneWord(owner->view());
                owner->view()->text->FinishUndo();
                moveCursorUpdate(true);
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
                
        case LFUN_BEGINNINGBUFSEL:
@@ -1658,7 +1754,7 @@ string LyXFunc::Dispatch(int ac,
                owner->view()->text->CursorTop(owner->view());
                owner->view()->text->FinishUndo();
                moveCursorUpdate(true);
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
                
        case LFUN_ENDBUFSEL:
@@ -1666,7 +1762,7 @@ string LyXFunc::Dispatch(int ac,
                owner->view()->text->CursorBottom(owner->view());
                owner->view()->text->FinishUndo();
                moveCursorUpdate(true);
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
 
                // --- text changing commands ------------------------
@@ -1694,18 +1790,19 @@ string LyXFunc::Dispatch(int ac,
        break;
                
        case LFUN_SETMARK:
-               if(owner->view()->text->mark_set) {
+               if (text->mark_set) {
                        owner->view()->beforeChange();
                        owner->view()->update(BufferView::SELECT|BufferView::FITCUR);
                        setMessage(N_("Mark removed"));
                } else {
                        owner->view()->beforeChange();
-                       owner->view()->text->mark_set = 1;
+                       text->mark_set = 1;
                        owner->view()->update(BufferView::SELECT|BufferView::FITCUR);
                        setMessage(N_("Mark set"));
                }
-               owner->view()->text->sel_cursor = 
-                       owner->view()->text->cursor;
+               text->sel_cursor = text->cursor;
+               if (text->inset_owner)
+                   owner->view()->updateInset(text->inset_owner, true);
                break;
                
        case LFUN_DELETE:
@@ -1721,7 +1818,7 @@ string LyXFunc::Dispatch(int ac,
                        owner->view()->cut();
                }
                moveCursorUpdate(false);
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                owner->view()->setState();
                break;
 
@@ -1772,25 +1869,31 @@ string LyXFunc::Dispatch(int ac,
        /* -------> Delete word forward. */
        case LFUN_DELETE_WORD_FORWARD:
                owner->view()->update(BufferView::SELECT|BufferView::FITCUR);
-               owner->view()->text->DeleteWordForward(owner->view());
+               text->DeleteWordForward(owner->view());
+               if (text->inset_owner)
+                   owner->view()->updateInset(text->inset_owner, true);
                owner->view()->update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
                moveCursorUpdate(false);
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
 
                /* -------> Delete word backward. */
        case LFUN_DELETE_WORD_BACKWARD:
                owner->view()->update(BufferView::SELECT|BufferView::FITCUR);
-               owner->view()->text->DeleteWordBackward(owner->view());
+               text->DeleteWordBackward(owner->view());
+               if (text->inset_owner)
+                   owner->view()->updateInset(text->inset_owner, true);
                owner->view()->update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
                moveCursorUpdate(false);
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
                
                /* -------> Kill to end of line. */
        case LFUN_DELETE_LINE_FORWARD:
                owner->view()->update(BufferView::SELECT|BufferView::FITCUR);
-               owner->view()->text->DeleteLineForward(owner->view());
+               text->DeleteLineForward(owner->view());
+               if (text->inset_owner)
+                   owner->view()->updateInset(text->inset_owner, true);
                owner->view()->update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
                moveCursorUpdate(false);
                break;
@@ -1799,9 +1902,10 @@ string LyXFunc::Dispatch(int ac,
        case LFUN_MARK_OFF:
                owner->view()->beforeChange();
                owner->view()->update(BufferView::SELECT|BufferView::FITCUR);
-               owner->view()->text->sel_cursor = 
-                       owner->view()->text->cursor;
+               text->sel_cursor = text->cursor;
                setMessage(N_("Mark off"));
+               if (text->inset_owner)
+                   owner->view()->updateInset(text->inset_owner, true);
                break;
 
                /* -------> Set mark on. */
@@ -1809,8 +1913,9 @@ string LyXFunc::Dispatch(int ac,
                owner->view()->beforeChange();
                owner->view()->text->mark_set = 1;
                owner->view()->update(BufferView::SELECT|BufferView::FITCUR);
-               owner->view()->text->sel_cursor = 
-                       owner->view()->text->cursor;
+               text->sel_cursor = text->cursor;
+               if (text->inset_owner)
+                   owner->view()->updateInset(text->inset_owner, true);
                setMessage(N_("Mark on"));
                break;
                
@@ -1829,7 +1934,7 @@ string LyXFunc::Dispatch(int ac,
                } else {
                        owner->view()->cut();
                }
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                owner->view()->setState();
        }
        break;
@@ -1873,7 +1978,7 @@ string LyXFunc::Dispatch(int ac,
                owner->view()->text->sel_cursor = 
                        owner->view()->text->cursor;
                owner->view()->setState();
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
        }
 
@@ -1885,7 +1990,7 @@ string LyXFunc::Dispatch(int ac,
                owner->view()->text->sel_cursor = 
                        owner->view()->text->cursor;
                owner->view()->setState();
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
                break;
        }
        
@@ -1920,7 +2025,7 @@ string LyXFunc::Dispatch(int ac,
                owner->view()->update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
                owner->view()->text->sel_cursor = cursor;
                owner->view()->setState();
-               owner->getMiniBuffer()->Set(CurrentState(owner->view()));
+               owner->showState();
        }
        break;
 
@@ -1933,11 +2038,8 @@ string LyXFunc::Dispatch(int ac,
                        cur_value = par->spacing.getValue();
                }
                
-#ifdef HAVE_SSTREAM
-               istringstream istr(argument);
-#else
-               istrstream istr(argument.c_str());
-#endif
+               istringstream istr(argument.c_str());
+
                string tmp;
                istr >> tmp;
                Spacing::Space new_spacing = cur_spacing;
@@ -1982,30 +2084,41 @@ string LyXFunc::Dispatch(int ac,
        case LFUN_HTMLURL:
        case LFUN_URL:
        {
-               InsetCommand * new_inset;
+               InsetCommandParams p;
                if (action == LFUN_HTMLURL)
-                       new_inset = new InsetUrl("htmlurl", "", "");
+                       p.setCmdName("htmlurl");
                else
-                       new_inset = new InsetUrl("url", "", "");
-               if (owner->view()->insertInset(new_inset))
-                       new_inset->Edit(owner->view(), 0, 0, 0);
+                       p.setCmdName("url");
+               owner->getDialogs()->createUrl( p.getAsString() );
+       }
+       break;
+                   
+       case LFUN_INSERT_URL:
+       {
+               InsetCommandParams p;
+               p.setFromString( argument );
+
+               InsetUrl * inset = new InsetUrl( p );
+               if (!owner->view()->insertInset(inset))
+                       delete inset;
                else
-                       delete new_inset;
+                       owner->view()->updateInset( inset, true );
        }
        break;
-       
+                   
        case LFUN_INSET_TEXT:
        {
-               InsetText * new_inset = new InsetText();
+               InsetText * new_inset = new InsetText;
                if (owner->view()->insertInset(new_inset))
                        new_inset->Edit(owner->view(), 0, 0, 0);
                else
                        delete new_inset;
        }
        break;
+       
        case LFUN_INSET_ERT:
        {
-               InsetERT * new_inset = new InsetERT();
+               InsetERT * new_inset = new InsetERT;
                if (owner->view()->insertInset(new_inset))
                        new_inset->Edit(owner->view(), 0, 0, 0);
                else
@@ -2015,7 +2128,7 @@ string LyXFunc::Dispatch(int ac,
        
        case LFUN_INSET_EXTERNAL:
        {
-               InsetExternal * new_inset = new InsetExternal();
+               InsetExternal * new_inset = new InsetExternal;
                if (owner->view()->insertInset(new_inset))
                        new_inset->Edit(owner->view(), 0, 0, 0);
                else
@@ -2025,7 +2138,7 @@ string LyXFunc::Dispatch(int ac,
        
        case LFUN_INSET_FOOTNOTE:
        {
-               InsetFoot * new_inset = new InsetFoot();
+               InsetFoot * new_inset = new InsetFoot;
                if (owner->view()->insertInset(new_inset))
                        new_inset->Edit(owner->view(), 0, 0, 0);
                else
@@ -2033,12 +2146,89 @@ string LyXFunc::Dispatch(int ac,
        }
        break;
 
+       case LFUN_INSET_MARGINAL:
+       {
+               InsetMarginal * new_inset = new InsetMarginal;
+               if (owner->view()->insertInset(new_inset))
+                       new_inset->Edit(owner->view(), 0, 0, 0);
+               else
+                       delete new_inset;
+       }
+       break;
+
+       case LFUN_INSET_MINIPAGE:
+       {
+               InsetMinipage * new_inset = new InsetMinipage;
+               if (owner->view()->insertInset(new_inset))
+                       new_inset->Edit(owner->view(), 0, 0, 0);
+               else
+                       delete new_inset;
+       }
+       break;
+
+       case LFUN_INSET_FLOAT:
+       {
+               // check if the float type exist
+               if (floatList.typeExist(argument)) {
+                       InsetFloat * new_inset = new InsetFloat(argument);
+                       if (owner->view()->insertInset(new_inset))
+                               new_inset->Edit(owner->view(), 0, 0, 0);
+                       else
+                               delete new_inset;
+               } else {
+                       lyxerr << "Non-existant float type: "
+                              << argument << endl;
+               }
+               
+       }
+       break;
+
+       case LFUN_INSET_LIST:
+       {
+               InsetList * new_inset = new InsetList;
+               if (owner->view()->insertInset(new_inset))
+                       new_inset->Edit(owner->view(), 0, 0, 0);
+               else
+                       delete new_inset;
+       }
+       break;
+
+       case LFUN_INSET_THEOREM:
+       {
+               InsetTheorem * new_inset = new InsetTheorem;
+               if (owner->view()->insertInset(new_inset))
+                       new_inset->Edit(owner->view(), 0, 0, 0);
+               else
+                       delete new_inset;
+       }
+       break;
+
+       case LFUN_INSET_CAPTION:
+       {
+               // Do we have a locking inset...
+               if (owner->view()->theLockingInset()) {
+                       lyxerr << "Locking inset code: "
+                              << static_cast<int>(owner->view()->theLockingInset()->LyxCode());
+                       InsetCaption * new_inset = new InsetCaption;
+                       new_inset->setOwner(owner->view()->theLockingInset());
+                       new_inset->SetAutoBreakRows(true);
+                       new_inset->SetDrawFrame(0, InsetText::LOCKED);
+                       new_inset->SetFrameColor(0, LColor::footnoteframe);
+                       if (owner->view()->insertInset(new_inset))
+                               new_inset->Edit(owner->view(), 0, 0, 0);
+                       else
+                               delete new_inset;
+               }
+       }
+       break;
+       
        case LFUN_INSET_TABULAR:
        {
                int r = 2, c = 2;
                if (!argument.empty())
-                       sscanf(argument.c_str(),"%d%d",&r,&c);
-               InsetTabular * new_inset = new InsetTabular(owner->buffer(),r,c);
+                       ::sscanf(argument.c_str(),"%d%d", &r, &c);
+               InsetTabular * new_inset =
+                       new InsetTabular(*owner->buffer(), r, c);
                if (owner->view()->insertInset(new_inset))
                        new_inset->Edit(owner->view(), 0, 0, 0);
                else
@@ -2052,7 +2242,7 @@ string LyXFunc::Dispatch(int ac,
        {
                LyXParagraph::size_type pos = 
                        owner->view()->text->cursor.pos();
-               if(pos < owner->view()->text->cursor.par()->size())
+               if (pos < owner->view()->text->cursor.par()->size())
                        //dispatch_buffer = owner->view()->text->
                        //      cursor.par()->text[pos];
                        dispatch_buffer =
@@ -2071,9 +2261,9 @@ string LyXFunc::Dispatch(int ac,
                
        case LFUN_SETXY:
        {
-               int  x;
-               long y;
-               sscanf(argument.c_str(), " %d %ld", &x, &y);
+               int x;
+               int y;
+               ::sscanf(argument.c_str(), " %d %d", &x, &y);
                owner->view()->text->SetCursorFromCoordinates(owner->view(), x, y);
        }
        break;
@@ -2086,9 +2276,9 @@ string LyXFunc::Dispatch(int ac,
        case LFUN_GETFONT:
        {
                LyXFont & font = owner->view()->text->current_font;
-                if(font.shape() == LyXFont::ITALIC_SHAPE)
+                if (font.shape() == LyXFont::ITALIC_SHAPE)
                        dispatch_buffer = 'E';
-                else if(font.shape() == LyXFont::SMALLCAPS_SHAPE)
+                else if (font.shape() == LyXFont::SMALLCAPS_SHAPE)
                        dispatch_buffer = 'N';
                 else
                        dispatch_buffer = '0';
@@ -2099,7 +2289,7 @@ string LyXFunc::Dispatch(int ac,
        case LFUN_GETLATEX:
        {
                LyXFont & font = owner->view()->text->current_font;
-                if(font.latex() == LyXFont::ON)
+                if (font.latex() == LyXFont::ON)
                        dispatch_buffer = 'L';
                 else
                        dispatch_buffer = '0';
@@ -2125,8 +2315,8 @@ string LyXFunc::Dispatch(int ac,
        case LFUN_GOTOFILEROW:
        {
                char file_name[100];
-               int  row;
-               sscanf(argument.c_str(), " %s %d", file_name, &row);
+               int row;
+               ::sscanf(argument.c_str(), " %s %d", file_name, &row);
 
                // Must replace extension of the file to be .lyx and get full path
                string s = ChangeExtension(string(file_name), ".lyx");
@@ -2145,10 +2335,28 @@ string LyXFunc::Dispatch(int ac,
        }
        break;
 
+       case LFUN_GOTO_PARAGRAPH:
+       {
+                istringstream istr(argument.c_str());
+
+               int id;
+               istr >> id;
+               LyXParagraph * par = owner->view()->text->GetParFromID(id);
+
+               // Set the cursor
+               owner->view()->text->SetCursor(owner->view(), par, 0);
+               owner->view()->setState();
+               owner->showState();
+
+               // Recenter screen
+               owner->view()->center();
+       }
+       break;
+
        case LFUN_APROPOS:
        case LFUN_GETTIP:
        {
-               int qa = lyxaction.LookupFunc(argument.c_str());
+               int const qa = lyxaction.LookupFunc(argument);
                setMessage(lyxaction.helpText(static_cast<kb_action>(qa)));
        }
        break;
@@ -2199,15 +2407,7 @@ string LyXFunc::Dispatch(int ac,
        case LFUN_PUSH_TOOLBAR:
        {
                int nth = strToInt(argument);
-               if (lyxerr.debugging(Debug::TOOLBAR)) {
-                       lyxerr << "LFUN_PUSH_TOOLBAR: argument = `"
-                              << argument << "'\n"
-                              << "LFUN_PUSH_TOOLBAR: nth = `"
-                              << nth << "'" << endl;
-               }
-               
                if (nth <= 0) {
-                       LyXBell();
                        setErrorMessage(N_("Push-toolbar needs argument > 0"));
                } else {
                        owner->getToolbar()->push(nth);
@@ -2217,7 +2417,7 @@ string LyXFunc::Dispatch(int ac,
        
        case LFUN_ADD_TO_TOOLBAR:
        {
-               if (lyxerr.debugging(Debug::TOOLBAR)) {
+               if (lyxerr.debugging(Debug::GUI)) {
                        lyxerr << "LFUN_ADD_TO_TOOLBAR:"
                                "argument = `" << argument << '\'' << endl;
                }
@@ -2225,7 +2425,6 @@ string LyXFunc::Dispatch(int ac,
                //lyxerr <<string("Argument: ") + argument);
                //lyxerr <<string("Tmp     : ") + tmp);
                if (tmp.empty()) {
-                       LyXBell();
                        setErrorMessage(N_("Usage: toolbar-add-to <LyX command>"));
                } else {
                        owner->getToolbar()->add(argument, false);
@@ -2265,20 +2464,21 @@ string LyXFunc::Dispatch(int ac,
        case LFUN_INSERT_MATRIX:
        {          
                if (owner->view()->available()) { 
-                       owner->view()->
-                               open_new_inset(new InsetFormula(false));
-                       owner->view()
-                               ->the_locking_inset
-                               ->LocalDispatch(owner->view(),
-                                               action,
-                                               argument);
+                       if (owner->view()->
+                           open_new_inset(new InsetFormula(false)))
+                       {
+                               owner->view()->theLockingInset()
+                                       ->LocalDispatch(owner->view(),
+                                                       action,
+                                                       argument);
+                       }
                }
        }          
        break;
               
        case LFUN_INSERT_MATH:
        {
-               math_insert_symbol(argument.c_str());
+               math_insert_symbol(argument);
        }
        break;
        
@@ -2296,8 +2496,8 @@ string LyXFunc::Dispatch(int ac,
                        if (s.empty())
                                setErrorMessage(N_("Missing argument"));
                        else {
-                               string s1 = token(s, ' ', 1);
-                               int na = s1.empty() ? 0: atoi(s1.c_str());
+                               string const s1 = token(s, ' ', 1);
+                               int const na = s1.empty() ? 0 : lyx::atoi(s1);
                                owner->view()->
                                        open_new_inset(new InsetFormulaMacro(token(s, ' ', 0), na));
                        }
@@ -2306,8 +2506,7 @@ string LyXFunc::Dispatch(int ac,
        break;
 
        case LFUN_MATH_MODE:   // Open or create a math inset
-       {
-               
+       {               
                if (owner->view()->available())
                        owner->view()->open_new_inset(new InsetFormula);
                setMessage(N_("Math editor mode"));
@@ -2318,30 +2517,42 @@ string LyXFunc::Dispatch(int ac,
        case LFUN_MATH_LIMITS:
        {
                setErrorMessage(N_("This is only allowed in math mode!"));
+       
+       }
+       break;
+
+       case LFUN_MATH_PANEL:
+       {
+               show_symbols_form(this);
        }
        break;
        
-       case LFUN_INSERT_CITATION:
-       {   
-               InsetCitation * new_inset = new InsetCitation();
-               // ale970405
-               // The note, if any, must be after the key, delimited
-               // by a | so both key and remark can have spaces.
-               if (!argument.empty()) {
-                       string lsarg(argument);
-                       if (contains(lsarg, "|")) {
-                               new_inset->setContents(token(lsarg, '|', 0));
-                               new_inset->setOptions(token(lsarg, '|', 1));
-                       } else
-                               new_inset->setContents(lsarg);
-                       if (!owner->view()->insertInset(new_inset))
-                               delete new_inset;
+       case LFUN_CITATION_CREATE:
+       {
+               // Should do this "at source"
+               InsetCommandParams p( "cite" );
+               
+               if (contains(argument, "|")) {
+                       p.setContents( token(argument, '|', 0) );
+                       p.setOptions(  token(argument, '|', 1) );
                } else {
-                       if (owner->view()->insertInset(new_inset))
-                               new_inset->Edit(owner->view(), 0, 0, 0);
-                       else
-                               delete new_inset;
+                       p.setContents( argument );
                }
+
+               owner->getDialogs()->createCitation( p.getAsString() );
+       }
+       break;
+                   
+       case LFUN_CITATION_INSERT:
+       {
+               InsetCommandParams p;
+               p.setFromString( argument );
+
+               InsetCitation * inset = new InsetCitation( p );
+               if (!owner->view()->insertInset(inset))
+                       delete inset;
+               else
+                       owner->view()->updateInset( inset, true );
        }
        break;
                    
@@ -2350,20 +2561,19 @@ string LyXFunc::Dispatch(int ac,
                // ale970405+lasgoutt970425
                // The argument can be up to two tokens separated 
                // by a space. The first one is the bibstyle.
-               string lsarg(argument);
-               string bibstyle = token(lsarg, ' ', 1);
+               string const db       = token(argument, ' ', 0);
+               string bibstyle = token(argument, ' ', 1);
                if (bibstyle.empty())
                        bibstyle = "plain";
-               InsetBibtex * new_inset 
-                       = new InsetBibtex(token(lsarg, ' ', 0),
-                                         bibstyle,
-                                         owner->buffer());
+
+               InsetCommandParams p( "BibTeX", db, bibstyle );
+               InsetBibtex * inset = new InsetBibtex(p);
                
-               if (owner->view()->insertInset(new_inset)) {
-                       if (lsarg.empty())
-                               new_inset->Edit(owner->view(), 0, 0, 0);
+               if (owner->view()->insertInset(inset)) {
+                       if (argument.empty())
+                               inset->Edit(owner->view(), 0, 0, 0);
                } else
-                       delete new_inset;
+                       delete inset;
        }
        break;
                
@@ -2398,87 +2608,96 @@ string LyXFunc::Dispatch(int ac,
        }
        break;
                
-       case LFUN_INDEX_INSERT:
-       case LFUN_INDEX_INSERT_LAST:
+       case LFUN_INDEX_CREATE:
        {
-               // Can't do that at the beginning of a paragraph.
-               if (owner->view()->text->cursor.pos() - 1 < 0)
-                       break;
+               InsetCommandParams p( "index" );
+               
+               if (argument.empty()) {
+                       // Get the word immediately preceding the cursor
+                       LyXParagraph::size_type curpos = 
+                               owner->view()->text->cursor.pos() - 1;
 
-               InsetIndex * new_inset = new InsetIndex();
-               if (!argument.empty()) {
-                       string lsarg(argument);
-                       new_inset->setContents(lsarg);
-                       if (!owner->view()->insertInset(new_inset))
-                               delete new_inset;
+                       string curstring;
+                       if (curpos >= 0 )
+                               curstring = owner->view()->text
+                                           ->cursor.par()->GetWord(curpos);
+
+                       p.setContents( curstring );
                } else {
-                       //reh 98/09/21
-                       //get the current word for an argument
-                       LyXParagraph::size_type lastpos = 
-                               owner->view()->text->cursor.pos() - 1;
-                       // Get the current word. note that this must be done
-                       // before inserting the inset, or the inset will
-                       // break the word
-                       string curstring(owner->view()
-                                        ->text->cursor.par()->GetWord(lastpos));
+                       p.setContents( argument );
+               }
 
-                       //make the new inset and write the current word into it
-                       InsetIndex * new_inset = new InsetIndex();
+               owner->getDialogs()->createIndex( p.getAsString() );
+       }
+       break;
+                   
+       case LFUN_INDEX_INSERT:
+       {
+               InsetCommandParams p;
+               p.setFromString(argument);
+               InsetIndex * inset = new InsetIndex(p);
 
-                       new_inset->setContents(curstring);
+               if (!owner->view()->insertInset(inset))
+                       delete inset;
+               else
+                       owner->view()->updateInset(inset, true);
+       }
+       break;
+                   
+       case LFUN_INDEX_INSERT_LAST:
+       {
+               // Get word immediately preceding the cursor
+               LyXParagraph::size_type curpos = 
+                       owner->view()->text->cursor.pos() - 1;
+               // Can't do that at the beginning of a paragraph
+               if (curpos < 0) break;
 
-                       //don't edit it if the call was to INSERT_LAST
-                       if(action != LFUN_INDEX_INSERT_LAST) {
-                               new_inset->Edit(owner->view(), 0, 0, 0);
-                       } else {
-                               //it looks blank on the screen unless
-                               //we do  something.  put it here.
+               string const curstring(owner->view()->text
+                                 ->cursor.par()->GetWord(curpos));
 
-                               // move the cursor to the returned value of lastpos
-                               // but only for the auto-insert
-                               owner->view()->text->cursor.pos(lastpos);
-                       }
+               InsetCommandParams p("index", curstring);
+               InsetIndex * inset = new InsetIndex(p);
 
-                       //put the new inset into the buffer.
-                       // there should be some way of knowing the user
-                       //cancelled & avoiding this, but i don't know how
-                       if (!owner->view()->insertInset(new_inset))
-                               delete new_inset;
-               }
+               if (!owner->view()->insertInset(inset))
+                       delete inset;
+               else
+                       owner->view()->updateInset(inset, true);
        }
        break;
-
+                   
        case LFUN_INDEX_PRINT:
        {
-               Inset * new_inset = new InsetPrintIndex(owner->buffer());
-               if (!owner->view()->insertInset(new_inset, "Standard", true))
-                       delete new_inset;
+               InsetCommandParams p("printindex");
+               Inset * inset = new InsetPrintIndex(p);
+               if (!owner->view()->insertInset(inset, "Standard", true))
+                       delete inset;
        }
        break;
 
        case LFUN_PARENTINSERT:
        {
                lyxerr << "arg " << argument << endl;
-               Inset * new_inset = new InsetParent(argument, owner->buffer());
-               if (!owner->view()->insertInset(new_inset, "Standard", true))
-                       delete new_inset;
+               InsetCommandParams p( "lyxparent", argument );
+               Inset * inset = new InsetParent(p, *owner->buffer());
+               if (!owner->view()->insertInset(inset, "Standard", true))
+                       delete inset;
        }
        break;
 
        case LFUN_CHILDINSERT:
        {
-               Inset * new_inset = new InsetInclude(argument,
-                                                    owner->buffer());
-               if (owner->view()->insertInset(new_inset, "Standard", true))
-                       new_inset->Edit(owner->view(), 0, 0, 0);
+               InsetCommandParams p( "Include", argument );
+               Inset * inset = new InsetInclude(p, *owner->buffer());
+               if (owner->view()->insertInset(inset, "Standard", true))
+                       inset->Edit(owner->view(), 0, 0, 0);
                else
-                       delete new_inset;
+                       delete inset;
        }
        break;
 
        case LFUN_CHILDOPEN:
        {
-               string filename =
+               string const filename =
                        MakeAbsPath(argument, 
                                    OnlyPath(owner->buffer()->fileName()));
                setMessage(N_("Opening child document ") +
@@ -2494,25 +2713,25 @@ string LyXFunc::Dispatch(int ac,
        case LFUN_INSERT_NOTE:
                owner->view()->insertNote();
                break;
-               
+#ifndef NEW_INSETS
        case LFUN_INSERTFOOTNOTE: 
        {
                LyXParagraph::footnote_kind kind;
-               if (argument == "footnote")
-                       { kind = LyXParagraph::FOOTNOTE; }
-               else if (argument == "margin")
-                       { kind = LyXParagraph::MARGIN; }
-               else if (argument == "figure")
-                       { kind = LyXParagraph::FIG; }
-               else if (argument == "table")
-                       { kind = LyXParagraph::TAB; }
-               else if (argument == "wide-fig")
-                       { kind = LyXParagraph::WIDE_FIG; }
-               else if (argument == "wide-tab")
-                       { kind = LyXParagraph::WIDE_TAB; }
-               else if (argument == "algorithm")
-                       { kind = LyXParagraph::ALGORITHM; }
-               else {
+               if (argument == "footnote") {
+                       kind = LyXParagraph::FOOTNOTE;
+               } else if (argument == "margin") {
+                       kind = LyXParagraph::MARGIN;
+               } else if (argument == "figure") {
+                       kind = LyXParagraph::FIG;
+               } else if (argument == "table") {
+                       kind = LyXParagraph::TAB;
+               } else if (argument == "wide-fig") {
+                       kind = LyXParagraph::WIDE_FIG;
+               } else if (argument == "wide-tab") {
+                       kind = LyXParagraph::WIDE_TAB;
+               } else if (argument == "algorithm") {
+                       kind = LyXParagraph::ALGORITHM;
+               else {
                        setErrorMessage(N_("Unknown kind of footnote"));
                        break;
                }
@@ -2521,13 +2740,9 @@ string LyXFunc::Dispatch(int ac,
                owner->view()->setState();
        }
        break;
-       
-       case LFUN_BUFFERBULLETSSELECT:
-               bulletForm();
-               break;
-               
+#endif
        case LFUN_TOGGLECURSORFOLLOW:
-               cursor_follows_scrollbar = !cursor_follows_scrollbar;
+               lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
                break;
                
        case LFUN_KMAP_OFF:             // keymap off
@@ -2548,6 +2763,7 @@ string LyXFunc::Dispatch(int ac,
 
        case LFUN_SELFINSERT:
        {
+               LyXFont const old_font(owner->view()->text->real_current_font);
                for (string::size_type i = 0; i < argument.length(); ++i) {
                        owner->view()->text->InsertChar(owner->view(), argument[i]);
                        // This needs to be in the loop, or else we
@@ -2557,6 +2773,11 @@ string LyXFunc::Dispatch(int ac,
                owner->view()->text->sel_cursor = 
                        owner->view()->text->cursor;
                moveCursorUpdate(false);
+
+               // real_current_font.number can change so we need to 
+               // update the minibuffer
+               if (old_font != owner->view()->text->real_current_font)
+                       owner->showState();
        }
        break;
 
@@ -2584,7 +2805,8 @@ string LyXFunc::Dispatch(int ac,
                else 
                        arg = lyxrc.date_insert_format;
                char datetmp[32];
-               int datetmp_len = strftime(datetmp, 32, arg.c_str(), now_tm);
+               int const datetmp_len =
+                       ::strftime(datetmp, 32, arg.c_str(), now_tm);
                for (int i = 0; i < datetmp_len; i++) {
                        owner->view()->text->InsertChar(owner->view(), datetmp[i]);
                        owner->view()->update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
@@ -2595,6 +2817,10 @@ string LyXFunc::Dispatch(int ac,
        }
        break;
 
+       case LFUN_DIALOG_PREFERENCES:
+               owner->getDialogs()->showPreferences();
+               break;
+               
        case LFUN_SAVEPREFERENCES:
        {
                Path p(user_lyxdir);
@@ -2602,10 +2828,27 @@ string LyXFunc::Dispatch(int ac,
        }
        break;
 
+       case LFUN_SCREEN_FONT_UPDATE:
+       {
+               // handle the screen font changes.
+               // 
+               lyxrc.set_font_norm_type();
+               fontloader.update();
+               // Of course we should only do the resize and the textcache.clear
+               // if values really changed...but not very important right now. (Lgb)
+               // All buffers will need resize
+               bufferlist.resize();
+               // We also need to empty the textcache so that
+               // the buffer will be formatted correctly after
+               // a zoom change.
+               textcache.clear();
+       }
+       break;
+
        case LFUN_SET_COLOR:
        {
-               string lyx_name, x11_name;
-               x11_name = split(argument, lyx_name, ' ');
+               string lyx_name;
+               string const x11_name = split(argument, lyx_name, ' ');
                if (lyx_name.empty() || x11_name.empty()) {
                        LyXBell();
                        setErrorMessage(N_("Syntax: set-color <lyx_name>"
@@ -2614,11 +2857,12 @@ string LyXFunc::Dispatch(int ac,
                        }
 
                if (!lcolor.setColor(lyx_name, x11_name)) {
-                       static string err1 (N_("Set-color \""));
-                       static string err2 (N_("\" failed - color is undefined "
-                                               "or may not be redefined"));
+                       static string const err1 (N_("Set-color \""));
+                       static string const err2 (
+                               N_("\" failed - color is undefined "
+                                  "or may not be redefined"));
                        LyXBell();
-                       setErrorMessage(err1 + lyx_name + err2);
+                       setErrorMessage(_(err1) + lyx_name + _(err2));
                        break;
                }
                lyxColorHandler->updateColor(lcolor.getFromLyXName(lyx_name));
@@ -2628,7 +2872,7 @@ string LyXFunc::Dispatch(int ac,
 
        case LFUN_UNKNOWN_ACTION:
        {
-               if(!owner->buffer()) {
+               if (!owner->buffer()) {
                        LyXBell();
                        setErrorMessage(N_("No document open"));
                        break;
@@ -2648,7 +2892,7 @@ string LyXFunc::Dispatch(int ac,
                         * "auto_region_delete", which defaults to
                         * true (on). */
                
-                       if ( lyxrc.auto_region_delete ) {
+                       if (lyxrc.auto_region_delete) {
                                if (owner->view()->text->selection){
                                        owner->view()->text->CutSelection(owner->view(), false);
                                        owner->view()->update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
@@ -2656,7 +2900,7 @@ string LyXFunc::Dispatch(int ac,
                        }
                        
                        owner->view()->beforeChange();
-                       
+                       LyXFont const old_font(owner->view()->text->real_current_font);
                        for (string::size_type i = 0;
                             i < argument.length(); ++i) {
                                if (greek_kb_flag) {
@@ -2671,6 +2915,11 @@ string LyXFunc::Dispatch(int ac,
                        owner->view()->text->sel_cursor = 
                                owner->view()->text->cursor;
                        moveCursorUpdate(false);
+
+                       // real_current_font.number can change so we need to
+                       // update the minibuffer
+                       if (old_font != owner->view()->text->real_current_font)
+                               owner->showState();
                        return string();
                } else {
                        // why is an "Unknown action" with empty
@@ -2680,18 +2929,20 @@ string LyXFunc::Dispatch(int ac,
                        setErrorMessage(N_("Unknown action"));
                }
                break;
+       }
+
        default:
                lyxerr << "A truly unknown func!" << endl;
                break;
-       }
        } // end of switch
   exit_with_message:
 
-       string res = getMessage();
+       string const res = getMessage();
 
        if (res.empty()) {
                if (!commandshortcut.empty()) {
-                       string newbuf = owner->getMiniBuffer()->GetText();
+                       string const newbuf =
+                               owner->getMiniBuffer()->GetText();
                        if (newbuf != commandshortcut) {
                                owner->getMiniBuffer()->Set(newbuf
                                                            + " " +
@@ -2699,8 +2950,10 @@ string LyXFunc::Dispatch(int ac,
                        }
                }
        } else {
-               owner->getMiniBuffer()->Set(string(_(res.c_str()))
-                                           + " " + commandshortcut);
+               string msg(_(res));
+               msg += " ";
+               msg += commandshortcut;
+               owner->getMiniBuffer()->Set(msg);
        }
 
        return res;
@@ -2716,41 +2969,45 @@ void LyXFunc::setupLocalKeymap()
 
 void LyXFunc::MenuNew(bool fromTemplate)
 {
-       string fname, initpath = lyxrc.document_path;
+       string initpath = lyxrc.document_path;
        LyXFileDlg fileDlg;
 
        if (owner->view()->available()) {
-               string trypath = owner->buffer()->filepath;
+               string const trypath = owner->buffer()->filepath;
                // If directory is writeable, use this as default.
                if (IsDirWriteable(trypath) == 1)
                        initpath = trypath;
        }
 
-       ProhibitInput(owner->view());
-       fileDlg.SetButton(0, _("Documents"), lyxrc.document_path);
-       fileDlg.SetButton(1, _("Templates"), lyxrc.template_path);
-       fname = fileDlg.Select(_("Enter Filename for new document"), 
-                              initpath, "*.lyx", _("newfile"));
-       AllowInput(owner->view());
+       static int newfile_number = 0;
+       string s;
        
-       if (fname.empty()) {
-               owner->getMiniBuffer()->Set(_("Canceled."));
-               lyxerr.debug() << "New Document Cancelled." << endl;
-               return;
-       }
-        
-       // get absolute path of file and make sure the filename ends
-       // with .lyx
-       string s = MakeAbsPath(fname);
-       if (!IsLyXFilename(s))
-               s += ".lyx";
-
-       // Check if the document already is open
-       if (bufferlist.exists(s)){
-               switch(AskConfirmation(_("Document is already open:"), 
-                                      MakeDisplayPath(s, 50),
-                                      _("Do you want to close that document now?\n"
-                                        "('No' will just switch to the open version)")))
+       if (lyxrc.new_ask_filename) {
+               ProhibitInput(owner->view());
+               fileDlg.SetButton(0, _("Documents"), lyxrc.document_path);
+               fileDlg.SetButton(1, _("Templates"), lyxrc.template_path);
+               string fname = fileDlg.Select(_("Enter Filename for new document"), 
+                                      initpath, "*.lyx", _("newfile"));
+               AllowInput(owner->view());
+       
+               if (fname.empty()) {
+                       owner->getMiniBuffer()->Set(_("Canceled."));
+                       lyxerr.debug() << "New Document Cancelled." << endl;
+                       return;
+               }
+       
+               // get absolute path of file and make sure the filename ends
+               // with .lyx
+               s = MakeAbsPath(fname);
+               if (!IsLyXFilename(s))
+                       s += ".lyx";
+
+               // Check if the document already is open
+               if (bufferlist.exists(s)) {
+                       switch (AskConfirmation(_("Document is already open:"), 
+                                              MakeDisplayPath(s, 50),
+                                              _("Do you want to close that document now?\n"
+                                                "('No' will just switch to the open version)")))
                        {
                        case 1: // Yes: close the document
                                if (!bufferlist.close(bufferlist.getBuffer(s)))
@@ -2764,25 +3021,36 @@ void LyXFunc::MenuNew(bool fromTemplate)
                                owner->getMiniBuffer()->Set(_("Canceled."));
                                return;
                        }
-       }
-        
-       // Check whether the file already exists
-       if (IsLyXFilename(s)) {
+               }
+               // Check whether the file already exists
+               if (IsLyXFilename(s)) {
+                       FileInfo fi(s);
+                       if (fi.readable() &&
+                           AskQuestion(_("File already exists:"), 
+                                       MakeDisplayPath(s, 50),
+                                       _("Do you want to open the document?"))) {
+                               // loads document
+                               owner->getMiniBuffer()->Set(_("Opening document"), 
+                                                           MakeDisplayPath(s), "...");
+                               XFlush(fl_get_display());
+                               owner->view()->buffer(
+                                       bufferlist.loadLyXFile(s));
+                               owner->getMiniBuffer()->Set(_("Document"),
+                                                           MakeDisplayPath(s),
+                                                           _("opened."));
+                               return;
+                       }
+               }
+       } else {
+               s = AddName(lyxrc.document_path,
+                           "newfile" + tostr(++newfile_number) + ".lyx");
                FileInfo fi(s);
-               if (fi.readable() &&
-                   AskQuestion(_("File already exists:"), 
-                               MakeDisplayPath(s, 50),
-                               _("Do you want to open the document?"))) {
-                       // loads document
-                       owner->getMiniBuffer()->Set(_("Opening document"), 
-                                                   MakeDisplayPath(s), "...");
-                       XFlush(fl_display);
-                       owner->view()->buffer(
-                               bufferlist.loadLyXFile(s));
-                       owner->getMiniBuffer()->Set(_("Document"),
-                                                   MakeDisplayPath(s),
-                                                   _("opened."));
-                       return;
+               while (bufferlist.exists(s) || fi.readable()) {
+                       ++newfile_number;
+                       s = AddName(lyxrc.document_path,
+                                   "newfile" + tostr(newfile_number) +
+                                   ".lyx");
+                       fi.newFile(s);
                }
        }
 
@@ -2790,11 +3058,12 @@ void LyXFunc::MenuNew(bool fromTemplate)
        string templname;
        if (fromTemplate) {
                ProhibitInput(owner->view());
-               fname = fileDlg.Select(_("Choose template"),
-                                      lyxrc.template_path,
-                                      "*.lyx");
-                templname = fname;
+               string const fname = fileDlg.Select(_("Choose template"),
+                                                   lyxrc.template_path,
+                                                   "*.lyx");
                AllowInput(owner->view());
+               if (fname.empty()) return;
+                templname = fname;
        }
   
        // find a free buffer
@@ -2809,7 +3078,7 @@ void LyXFunc::MenuOpen()
        LyXFileDlg fileDlg;
   
        if (owner->view()->available()) {
-               string trypath = owner->buffer()->filepath;
+               string const trypath = owner->buffer()->filepath;
                // If directory is writeable, use this as default.
                if (IsDirWriteable(trypath) == 1)
                        initpath = trypath;
@@ -2851,25 +3120,21 @@ void LyXFunc::MenuOpen()
        }
 }
 
-// returns filename if file must be imported,
-// empty string if either file not found or already loaded
-// checks for running without gui are missing.
 
-void LyXFunc::doImportHelper(
-       string const & file,          // filename (possibly empty)
-       string const & text,          // info when asking for filename
-       string const & pattern,       // filetype
-       bool func(BufferView *, string const &)     // the real import function
-)
+// checks for running without gui are missing.
+void LyXFunc::doImport(string const & argument)
 {
-       string filename = file;
+       string format;
+       string filename = split(argument, format, ' ');
+       lyxerr.debug() << "LyXFunc::doImport: " << format 
+                      << " file: " << filename << endl;
 
        if (filename.empty()) { // need user interaction
                string initpath = lyxrc.document_path;
                LyXFileDlg fileDlg;
                
                if (owner->view()->available()) {
-                       string trypath = owner->buffer()->filepath;
+                       string const trypath = owner->buffer()->filepath;
                        // If directory is writeable, use this as default.
                        if (IsDirWriteable(trypath) == 1)
                                initpath = trypath;
@@ -2880,7 +3145,10 @@ void LyXFunc::doImportHelper(
                fileDlg.SetButton(0, _("Documents"), lyxrc.document_path);
                fileDlg.SetButton(1, _("Examples"), 
                                        AddPath(system_lyxdir, "examples"));
-               filename = fileDlg.Select(text, initpath, pattern);
+               string const text = _("Select ") + formats.PrettyName(format)
+                       + _(" file to import");
+               string const extension = "*." + formats.Extension(format);
+               filename = fileDlg.Select(text, initpath, extension);
                AllowInput(owner->view());
  
                // check selected filename
@@ -2895,11 +3163,11 @@ void LyXFunc::doImportHelper(
        // get absolute path of file
        filename = MakeAbsPath(filename);
 
-       string lyxfile = ChangeExtension(filename, ".lyx");
+       string const lyxfile = ChangeExtension(filename, ".lyx");
 
        // Check if the document already is open
        if (bufferlist.exists(lyxfile)) {
-               switch(AskConfirmation(_("Document is already open:"), 
+               switch (AskConfirmation(_("Document is already open:"), 
                                       MakeDisplayPath(lyxfile, 50),
                                       _("Do you want to close that document now?\n"
                                         "('No' will just switch to the open version)")))
@@ -2919,7 +3187,7 @@ void LyXFunc::doImportHelper(
        }
 
        // Check if a LyX document by the same root exists in filesystem
-       FileInfo f(lyxfile, true);
+       FileInfo const f(lyxfile, true);
        if (f.exist() && !AskQuestion(_("A document by the name"), 
                                      MakeDisplayPath(lyxfile),
                                      _("already exists. Overwrite?"))) {
@@ -2928,78 +3196,7 @@ void LyXFunc::doImportHelper(
        }
        // filename should be valid now
 
-       // notify user of import ahead
-       string displaypath = MakeDisplayPath(filename);
-       owner->getMiniBuffer()->Set(_("Importing"), displaypath, "...");
-
-       // call real importer
-       bool result = func(owner->view(), filename);
-
-       // we are done
-       if (result)
-               owner->getMiniBuffer()->Set(displaypath, _("imported."));
-       else
-               owner->getMiniBuffer()->Set(displaypath, _(": import failed."));
-}
-
-static
-bool doImportASCIIasLines(BufferView * view, string const & filename)
-{
-       view->buffer(bufferlist.newFile(filename, string()));
-       InsertAsciiFile(view, filename, false);
-       return true;
-}
-
-static
-bool doImportASCIIasParagraphs(BufferView * view, string const & filename)
-{
-       view->buffer(bufferlist.newFile(filename, string()));
-       InsertAsciiFile(view, filename, true);
-       return true;
-}
-
-static
-bool doImportLaTeX(BufferView * view, string const & filename)
-{
-       ImportLaTeX myImport(filename);
-       Buffer * openbuf = myImport.run();
-       if (openbuf) { 
-               view->buffer(openbuf);
-               return true;
-       }
-       else
-               return false;
-}
-
-static
-bool doImportNoweb(BufferView * view, string const & filename)
-{
-       ImportNoweb myImport(filename);
-       Buffer * openbuf = myImport.run();
-       if (openbuf) { 
-               view->buffer(openbuf);
-               return true;
-       }
-       else
-               return false;
-}
-
-static
-bool doImportLinuxDoc(BufferView *, string const & filename)
-{
-       // run sgml2lyx
-       string tmp = lyxrc.linuxdoc_to_lyx_command + filename;
-       Systemcalls one;
-       Buffer * buf = 0;
-
-       int result = one.startscript(Systemcalls::System, tmp);
-       if (result == 0) {
-               string filename = ChangeExtension(filename, ".lyx");
-               // File was generated without problems. Load it.
-               buf = bufferlist.loadLyXFile(filename);
-       }
-
-       return result == 0;
+       Importer::Import(owner, filename, format);
 }
 
 
@@ -3013,7 +3210,7 @@ void LyXFunc::MenuInsertLyXFile(string const & filen)
                LyXFileDlg fileDlg;
 
                if (owner->view()->available()) {
-                       string trypath = owner->buffer()->filepath;
+                       string const trypath = owner->buffer()->filepath;
                        // If directory is writeable, use this as default.
                        if (IsDirWriteable(trypath) == 1)
                                initpath = trypath;
@@ -3044,7 +3241,7 @@ void LyXFunc::MenuInsertLyXFile(string const & filen)
        // Inserts document
        owner->getMiniBuffer()->Set(_("Inserting document"),
                                    MakeDisplayPath(filename), "...");
-       bool res = owner->view()->insertLyXFile(filename);
+       bool const res = owner->view()->insertLyXFile(filename);
        if (res) {
                owner->getMiniBuffer()->Set(_("Document"),
                                            MakeDisplayPath(filename),
@@ -3055,40 +3252,10 @@ void LyXFunc::MenuInsertLyXFile(string const & filen)
        }
 }
 
-void LyXFunc::doImport(string const & argument)
-{
-       string type;
-       string filename = split(argument, type, ' ');
-       lyxerr.debug() << "LyXFunc::doImport: " << type 
-                      << " file: " << filename << endl;
-
-       if (type == "latex") 
-               doImportHelper(filename,
-                              _("Select LaTeX file to import"), "*.tex", 
-                              doImportLaTeX);
-       else if (type == "ascii") 
-               doImportHelper(filename,
-                              _("Select ASCII file to import"), "*.txt", 
-                              doImportASCIIasLines);
-       else if (type == "asciiparagraph") 
-               doImportHelper(filename,
-                              _("Select ASCII file to import"), "*.txt", 
-                              doImportASCIIasParagraphs);
-       else if (type == "noweb") 
-               doImportHelper(filename,
-                              _("Select NoWeb file to import"), "*.nw", 
-                              doImportNoweb);
-       else if (type == "linuxdoc") 
-               doImportHelper(filename,
-                              _("Select LinuxDoc file to import"), "*.doc", 
-                              doImportLinuxDoc);
-       else 
-               setErrorMessage(string(N_("Unknown import type: ")) + type);
-}
 
 void LyXFunc::reloadBuffer()
 {
-       string fn = owner->buffer()->fileName();
+       string const fn = owner->buffer()->fileName();
        if (bufferlist.close(owner->buffer()))
                owner->view()->buffer(bufferlist.loadLyXFile(fn));
 }
@@ -3102,8 +3269,7 @@ void LyXFunc::CloseBuffer()
                        // set variables that don't exist
                        // since there's no current buffer
                        owner->getDialogs()->hideBufferDependent();
-               }
-               else {
+               } else {
                        owner->view()->buffer(bufferlist.first());
                }
        }
@@ -3114,13 +3280,12 @@ Inset * LyXFunc::getInsetByCode(Inset::Code code)
 {
        LyXCursor cursor = owner->view()->text->cursor;
        Buffer * buffer = owner->view()->buffer();
-       for (Buffer::inset_iterator it = Buffer::inset_iterator(cursor.par(),
-                                                               cursor.pos());
-            it != buffer->inset_iterator_end(); ++it) {
-               if ((*it)->LyxCode() == code)
-                       return *it;
-       }
-       return 0;
+       Buffer::inset_iterator it =
+               find_if(Buffer::inset_iterator(cursor.par(),
+                                              cursor.pos()),
+                       buffer->inset_iterator_end(),
+                       compare_memfun(&Inset::LyxCode, code));
+       return it != buffer->inset_iterator_end() ? (*it) : 0;
 }