]> git.lyx.org Git - lyx.git/blobdiff - src/BufferView_pimpl.C
redraw fix 1.
[lyx.git] / src / BufferView_pimpl.C
index 2c5898fa4db131e386f4b8717b766735dc330965..f2a70a68db3e8ef36a40172cfbb3992a9dc13701 100644 (file)
@@ -1,3 +1,11 @@
+/**
+ * \file BufferView_pimpl.C
+ * Copyright 2002 the LyX Team
+ * Read the file COPYING
+ *
+ * \author various
+ */
+
 #include <config.h>
 
 #ifdef __GNUG__
 #endif
 
 #include "BufferView_pimpl.h"
-#include "WorkArea.h"
-#include "lyxscreen.h"
+#include "frontends/WorkArea.h"
+#include "frontends/screen.h"
+#include "frontends/LyXScreenFactory.h"
+#include "frontends/WorkAreaFactory.h"
+#include "frontends/Dialogs.h"
+#include "frontends/Alert.h"
+#include "frontends/FileDialog.h"
 #include "lyxtext.h"
 #include "lyxrow.h"
 #include "paragraph.h"
-#include "LyXView.h"
+#include "frontends/LyXView.h"
 #include "commandtags.h"
 #include "lyxfunc.h"
 #include "debug.h"
-#include "font.h"
 #include "bufferview_funcs.h"
 #include "TextCache.h"
 #include "bufferlist.h"
 #include "undo_funcs.h"
 #include "lyxtextclasslist.h"
 
-#include "frontends/Dialogs.h"
-#include "frontends/Alert.h"
-#include "frontends/FileDialog.h"
-
 #include "insets/insetbib.h"
 #include "insets/insettext.h"
 #include "insets/inseturl.h"
 
 #include "mathed/formulabase.h"
 
+#include "graphics/Previews.h"
+
 #include "support/LAssert.h"
 #include "support/lstrings.h"
 #include "support/filetools.h"
 #include "support/lyxfunctional.h"
 
+#include <boost/bind.hpp>
+
+#include <cstdio>
 #include <ctime>
 #include <unistd.h>
 #include <sys/wait.h>
 
 extern string current_layout;
 
+#ifndef CXX_GLOBAL_CSTD
+using std::tm;
+using std::localtime;
+using std::time;
+using std::setlocale;
+using std::strftime;
+#endif
+
 using std::vector;
 using std::find_if;
 using std::find;
@@ -82,12 +103,11 @@ using std::pair;
 using std::endl;
 using std::make_pair;
 using std::min;
-using SigC::slot;
 
 using lyx::pos_type;
 using lyx::textclass_type;
 
-/* the selection possible is needed, that only motion events are 
+/* the selection possible is needed, that only motion events are
  * used, where the bottom press event was on the drawing area too */
 bool selection_possible = false;
 
@@ -101,73 +121,60 @@ namespace {
 
 const unsigned int saved_positions_num = 20;
 
-inline
-void waitForX()
-{
-       XSync(fl_get_display(), 0);
-}
-
-
-void SetXtermCursor(Window win)
-{
-       static Cursor cursor;
-       static bool cursor_undefined = true;
-       if (cursor_undefined) {
-               cursor = XCreateFontCursor(fl_get_display(), XC_xterm);
-               XFlush(fl_get_display());
-               cursor_undefined = false;
-       }
-       XDefineCursor(fl_get_display(), win, cursor);
-       XFlush(fl_get_display());
-}
 
 } // anon namespace
 
 
 BufferView::Pimpl::Pimpl(BufferView * b, LyXView * o,
             int xpos, int ypos, int width, int height)
-       : bv_(b), owner_(o), buffer_(0),
-         current_scrollbar_value(0), cursor_timeout(400),
-         workarea_(xpos, ypos, width, height), using_xterm_cursor(false),
-         inset_slept(false)
+       : bv_(b), owner_(o), buffer_(0), cursor_timeout(400),
+         using_xterm_cursor(false)
 {
+       workarea_.reset(WorkAreaFactory::create(xpos, ypos, width, height));
+       screen_.reset(LyXScreenFactory::create(workarea()));
+
        // Setup the signals
-       workarea_.scrollCB.connect(slot(this, &BufferView::Pimpl::scrollCB));
-       workarea_.workAreaExpose
-               .connect(slot(this, &BufferView::Pimpl::workAreaExpose));
-       workarea_.workAreaEnter
-               .connect(slot(this, &BufferView::Pimpl::enterView));
-       workarea_.workAreaLeave
-               .connect(slot(this, &BufferView::Pimpl::leaveView));
-       workarea_.workAreaButtonPress
-               .connect(slot(this, &BufferView::Pimpl::workAreaButtonPress));
-       workarea_.workAreaButtonRelease
-               .connect(slot(this,
-                             &BufferView::Pimpl::workAreaButtonRelease));
-       workarea_.workAreaMotionNotify
-               .connect(slot(this, &BufferView::Pimpl::workAreaMotionNotify));
-       workarea_.workAreaDoubleClick
-               .connect(slot(this, &BufferView::Pimpl::doubleClick));
-       workarea_.workAreaTripleClick
-               .connect(slot(this, &BufferView::Pimpl::tripleClick));
-       workarea_.workAreaKeyPress
-               .connect(slot(this, &BufferView::Pimpl::workAreaKeyPress));
-       workarea_.selectionRequested
-               .connect(slot(this, &BufferView::Pimpl::selectionRequested)); 
-       workarea_.selectionLost
-               .connect(slot(this, &BufferView::Pimpl::selectionLost));
-       
-       cursor_timeout.timeout.connect(slot(this,
-                                           &BufferView::Pimpl::cursorToggle));
+       workarea().scrollDocView.connect(boost::bind(&BufferView::Pimpl::scrollDocView, this, _1));
+       workarea().workAreaResize
+               .connect(boost::bind(&BufferView::Pimpl::workAreaResize, this));
+       workarea().workAreaButtonPress
+               .connect(boost::bind(&BufferView::Pimpl::workAreaButtonPress, this, _1, _2, _3));
+       workarea().workAreaButtonRelease
+               .connect(boost::bind(&BufferView::Pimpl::workAreaButtonRelease, this, _1, _2, _3));
+       workarea().workAreaMotionNotify
+               .connect(boost::bind(&BufferView::Pimpl::workAreaMotionNotify, this, _1, _2, _3));
+       workarea().workAreaDoubleClick
+               .connect(boost::bind(&BufferView::Pimpl::doubleClick, this, _1, _2, _3));
+       workarea().workAreaTripleClick
+               .connect(boost::bind(&BufferView::Pimpl::tripleClick, this, _1, _2, _3));
+       workarea().workAreaKeyPress
+               .connect(boost::bind(&BufferView::Pimpl::workAreaKeyPress, this, _1, _2));
+       workarea().selectionRequested
+               .connect(boost::bind(&BufferView::Pimpl::selectionRequested, this));
+       workarea().selectionLost
+               .connect(boost::bind(&BufferView::Pimpl::selectionLost, this));
+
+       cursor_timeout.timeout.connect(boost::bind(&BufferView::Pimpl::cursorToggle, this));
        cursor_timeout.start();
-       workarea_.setFocus();
        saved_positions.resize(saved_positions_num);
 }
 
 
-Painter & BufferView::Pimpl::painter() 
+WorkArea & BufferView::Pimpl::workarea() const
+{
+       return *workarea_.get();
+}
+
+
+LyXScreen & BufferView::Pimpl::screen() const
+{
+       return *screen_.get();
+}
+
+
+Painter & BufferView::Pimpl::painter() const
 {
-       return workarea_.getPainter();
+       return workarea().getPainter();
 }
 
 
@@ -176,17 +183,16 @@ void BufferView::Pimpl::buffer(Buffer * b)
        lyxerr[Debug::INFO] << "Setting buffer in BufferView ("
                            << b << ")" << endl;
        if (buffer_) {
-               insetSleep();
                buffer_->delUser(bv_);
 
                // Put the old text into the TextCache, but
                // only if the buffer is still loaded.
                // Also set the owner of the test to 0
                //              bv_->text->owner(0);
-               textcache.add(buffer_, workarea_.workWidth(), bv_->text);
+               textcache.add(buffer_, workarea().workWidth(), bv_->text);
                if (lyxerr.debugging())
                        textcache.show(lyxerr, "BufferView::buffer");
-               
+
                bv_->text = 0;
        }
 
@@ -194,10 +200,6 @@ void BufferView::Pimpl::buffer(Buffer * b)
        buffer_ = b;
 
        if (bufferlist.getState() == BufferList::CLOSING) return;
-       
-       // Nuke old image
-       // screen is always deleted when the buffer is changed.
-       screen_.reset(0);
 
        // If we are closing the buffer, use the first buffer as current
        if (!buffer_) {
@@ -207,29 +209,22 @@ void BufferView::Pimpl::buffer(Buffer * b)
        if (buffer_) {
                lyxerr[Debug::INFO] << "Buffer addr: " << buffer_ << endl;
                buffer_->addUser(bv_);
+
                // If we don't have a text object for this, we make one
                if (bv_->text == 0) {
                        resizeCurrentBuffer();
-               } else {
-                       updateScreen();
-                       updateScrollbar();
                }
-               bv_->text->first_y = screen_->topCursorVisible(bv_->text);
-               owner_->updateMenubar();
-               owner_->updateToolbar();
+
+               // FIXME: needed when ?
+               bv_->text->first_y = screen().topCursorVisible(bv_->text->cursor, bv_->text->first_y);
+
                // Similarly, buffer-dependent dialogs should be updated or
                // hidden. This should go here because some dialogs (eg ToC)
                // require bv_->text.
                owner_->getDialogs()->updateBufferDependent(true);
-               redraw();
-               insetWakeup();
        } else {
                lyxerr[Debug::INFO] << "  No Buffer!" << endl;
-               owner_->updateMenubar();
-               owner_->updateToolbar();
                owner_->getDialogs()->hideBufferDependent();
-               updateScrollbar();
-               workarea_.redraw();
 
                // Also remove all remaining text's from the testcache.
                // (there should not be any!) (if there is any it is a
@@ -238,51 +233,33 @@ void BufferView::Pimpl::buffer(Buffer * b)
                        textcache.show(lyxerr, "buffer delete all");
                textcache.clear();
        }
-       // should update layoutchoice even if we don't have a buffer.
-       owner_->updateLayoutChoice();
 
+       repaint();
+       updateScrollbar();
+       owner_->updateMenubar();
+       owner_->updateToolbar();
+       owner_->updateLayoutChoice();
        owner_->updateWindowTitle();
-}
-
-
-void BufferView::Pimpl::resize(int xpos, int ypos, int width, int height)
-{
-       workarea_.resize(xpos, ypos, width, height);
-       update(bv_->text, SELECT);
-       redraw();
-}
 
-
-void BufferView::Pimpl::resize()
-{
-       if (buffer_)
-               resizeCurrentBuffer();
-}
-
-
-void BufferView::Pimpl::redraw()
-{
-       lyxerr[Debug::INFO] << "BufferView::redraw()" << endl;
-       workarea_.redraw();
+       if (grfx::Previews::activated() && buffer_)
+               grfx::Previews::get().generateBufferPreviews(buffer_);
 }
 
 
 bool BufferView::Pimpl::fitCursor()
 {
-       lyx::Assert(screen_.get());
-
        bool ret;
 
        if (bv_->theLockingInset()) {
                bv_->theLockingInset()->fitInsetCursor(bv_);
                ret = true;
        } else {
-               ret = screen_->fitCursor(bv_->text, bv_);
+               ret = screen().fitCursor(bv_->text, bv_);
        }
 
        bv_->owner()->getDialogs()->updateParagraph();
        if (ret)
-           updateScrollbar();
+               updateScrollbar();
        return ret;
 }
 
@@ -291,7 +268,7 @@ void BufferView::Pimpl::redoCurrentBuffer()
 {
        lyxerr[Debug::INFO] << "BufferView::redoCurrentBuffer" << endl;
        if (buffer_ && bv_->text) {
-               resize();
+               resizeCurrentBuffer();
                owner_->updateLayoutChoice();
        }
 }
@@ -300,12 +277,12 @@ void BufferView::Pimpl::redoCurrentBuffer()
 int BufferView::Pimpl::resizeCurrentBuffer()
 {
        lyxerr[Debug::INFO] << "resizeCurrentBuffer" << endl;
-       
+
        Paragraph * par = 0;
        Paragraph * selstartpar = 0;
        Paragraph * selendpar = 0;
        UpdatableInset * the_locking_inset = 0;
-       
+
        pos_type pos = 0;
        pos_type selstartpos = 0;
        pos_type selendpos = 0;
@@ -326,17 +303,20 @@ int BufferView::Pimpl::resizeCurrentBuffer()
                selection = bv_->text->selection.set();
                mark_set = bv_->text->selection.mark();
                the_locking_inset = bv_->theLockingInset();
+               buffer_->resizeInsets(bv_);
+               // I don't think the delete and new are necessary here we just could
+               // call only init! (Jug 20020419)
                delete bv_->text;
                bv_->text = new LyXText(bv_);
                bv_->text->init(bv_);
        } else {
                // See if we have a text in TextCache that fits
                // the new buffer_ with the correct width.
-               bv_->text = textcache.findFit(buffer_, workarea_.workWidth());
+               bv_->text = textcache.findFit(buffer_, workarea().workWidth());
                if (bv_->text) {
                        if (lyxerr.debugging()) {
                                lyxerr << "Found a LyXText that fits:\n";
-                               textcache.show(lyxerr, make_pair(buffer_, make_pair(workarea_.workWidth(), bv_->text)));
+                               textcache.show(lyxerr, make_pair(buffer_, make_pair(workarea().workWidth(), bv_->text)));
                        }
                        // Set the owner of the newly found text
                        //      bv_->text->owner(bv_);
@@ -345,14 +325,14 @@ int BufferView::Pimpl::resizeCurrentBuffer()
                } else {
                        bv_->text = new LyXText(bv_);
                        bv_->text->init(bv_);
+                       //buffer_->resizeInsets(bv_);
                }
        }
-       updateScreen();
 
        if (par) {
                bv_->text->selection.set(true);
-               /* at this point just to avoid the Delete-Empty-Paragraph
-                * Mechanism when setting the cursor */
+               // At this point just to avoid the Delete-Empty-Paragraph-
+               // Mechanism when setting the cursor.
                bv_->text->selection.mark(mark_set);
                if (selection) {
                        bv_->text->setCursor(bv_, selstartpar, selstartpos);
@@ -368,183 +348,99 @@ int BufferView::Pimpl::resizeCurrentBuffer()
                // remake the inset locking
                bv_->theLockingInset(the_locking_inset);
        }
-       bv_->text->first_y = screen_->topCursorVisible(bv_->text);
-#if 0
-       buffer_->resizeInsets(bv_);
-#endif
-       // this will scroll the screen such that the cursor becomes visible
-       updateScrollbar();
-       redraw();
+
+       bv_->text->first_y = screen().topCursorVisible(bv_->text->cursor, bv_->text->first_y);
 
        setState();
        owner_->allowInput();
 
-       /// clear the "Formatting Document" message 
+       /// clear the "Formatting Document" message
        owner_->message("");
 
        return 0;
 }
 
 
-void BufferView::Pimpl::updateScreen()
+void BufferView::Pimpl::repaint()
 {
        // Regenerate the screen.
-       screen_.reset(new LyXScreen(workarea_));
+       screen().redraw(bv_->text, bv_);
 }
 
 
 void BufferView::Pimpl::updateScrollbar()
 {
-       /* If the text is smaller than the working area, the scrollbar
-        * maximum must be the working area height. No scrolling will 
-        * be possible */
        if (!bv_->text) {
-               workarea_.setScrollbar(0, 1.0);
+               lyxerr[Debug::GUI] << "no text in updateScrollbar" << endl;
+               workarea().setScrollbarParams(0, 0, 0);
                return;
        }
 
-       long const text_height = bv_->text->height;
-       long const work_height = workarea_.height();
+       LyXText const & t = *bv_->text;
+       lyxerr[Debug::GUI] << "Updating scrollbar: h " << t.height << ", first_y "
+               << t.first_y << ", default height " << t.defaultHeight() << endl;
 
-       if (text_height <= work_height) {
-               workarea_.setScrollbarBounds(0.0, 0.0);
-               current_scrollbar_value = bv_->text->first_y;
-               workarea_.setScrollbar(current_scrollbar_value, 1.0);
-               return;
-       }
-       
-       double const lineh = bv_->text->defaultHeight();
-       double const slider_size =
-               (text_height == 0) ? 1.0 : 1.0 / double(text_height);
-       
-       static long old_text_height;
-       static double old_lineh;
-       static double old_slider_size;
-
-       if (text_height != old_text_height) {
-               workarea_.setScrollbarBounds(0.0,
-                                            text_height - work_height);
-               old_text_height = text_height;
-       }
-       if (lineh != old_lineh) {
-               workarea_.setScrollbarIncrements(lineh);
-               old_lineh = lineh;
-       }
-       if (current_scrollbar_value != bv_->text->first_y
-           || slider_size != old_slider_size) {
-               current_scrollbar_value = bv_->text->first_y;
-               workarea_.setScrollbar(current_scrollbar_value, slider_size);
-               old_slider_size = slider_size;
-       }
+       workarea().setScrollbarParams(t.height, t.first_y, t.defaultHeight());
 }
 
 
-// Callback for scrollbar slider
-void BufferView::Pimpl::scrollCB(double value)
+void BufferView::Pimpl::scrollDocView(int value)
 {
-       if (!buffer_) return;
+       lyxerr[Debug::GUI] << "scrollDocView of " << value << endl;
 
-       current_scrollbar_value = long(value);
-
-       if (current_scrollbar_value < 0)
-               current_scrollbar_value = 0;
-   
-       if (!screen_.get())
-               return;
+       if (!buffer_) return;
 
-       screen_->draw(bv_->text, bv_, current_scrollbar_value);
+       screen().draw(bv_->text, bv_, value);
 
        if (!lyxrc.cursor_follows_scrollbar) {
-               waitForX();
                return;
        }
+
        LyXText * vbt = bv_->text;
+
        int const height = vbt->defaultHeight();
        int const first = static_cast<int>((bv_->text->first_y + height));
-       int const last = static_cast<int>((bv_->text->first_y + workarea_.height() - height));
+       int const last = static_cast<int>((bv_->text->first_y + workarea().workHeight() - height));
 
        if (vbt->cursor.y() < first)
                vbt->setCursorFromCoordinates(bv_, 0, first);
        else if (vbt->cursor.y() > last)
                vbt->setCursorFromCoordinates(bv_, 0, last);
-
-       waitForX();
 }
 
 
-int BufferView::Pimpl::scrollUp(long time)
+int BufferView::Pimpl::scroll(long time)
 {
-       if (!buffer_) return 0;
-       if (!screen_.get()) return 0;
-   
-       double value = workarea_.getScrollbarValue();
-   
-       if (value == 0) return 0;
-
-       float add_value =  (bv_->text->defaultHeight()
-                           + float(time) * float(time) * 0.125);
-   
-       if (add_value > workarea_.height())
-               add_value = float(workarea_.height() -
-                                 bv_->text->defaultHeight());
-   
-       value -= add_value;
-
-       if (value < 0)
-               value = 0;
-   
-       workarea_.setScrollbarValue(value);
-   
-       scrollCB(value); 
-       return 0;
-}
+       if (!buffer_)
+               return 0;
 
+       LyXText const * t = bv_->text;
 
-int BufferView::Pimpl::scrollDown(long time)
-{
-       if (!buffer_) return 0;
-       if (!screen_.get()) return 0;
-   
-       double value = workarea_.getScrollbarValue();
-       pair<float, float> p = workarea_.getScrollbarBounds();
-       double const max = p.second;
-       
-       if (value == max) return 0;
-
-       float add_value =  (bv_->text->defaultHeight()
-                           + float(time) * float(time) * 0.125);
-   
-       if (add_value > workarea_.height())
-               add_value = float(workarea_.height() -
-                                 bv_->text->defaultHeight());
-   
-       value += add_value;
-   
-       if (value > max)
-               value = max;
-
-       workarea_.setScrollbarValue(value);
-       
-       scrollCB(value); 
+       double const diff = t->defaultHeight()
+               + double(time) * double(time) * 0.125;
+
+       scrollDocView(int(diff));
+       workarea().setScrollbarParams(t->height, t->first_y, t->defaultHeight());
        return 0;
 }
 
 
-void BufferView::Pimpl::workAreaKeyPress(KeySym keysym, unsigned int state)
+void BufferView::Pimpl::workAreaKeyPress(LyXKeySymPtr key,
+                                        key_modifier::state state)
 {
-       bv_->owner()->getLyXFunc()->processKeySym(keysym, state);
+       bv_->owner()->getLyXFunc()->processKeySym(key, state);
 }
 
 
-void BufferView::Pimpl::workAreaMotionNotify(int x, int y, unsigned int state)
+void BufferView::Pimpl::workAreaMotionNotify(int x, int y, mouse_button::state state)
 {
        // Only use motion with button 1
-       if (!(state & Button1MotionMask))
+       if (!(state & mouse_button::button1))
                return;
 
-       if (!buffer_ || !screen_.get()) return;
+       if (!buffer_)
+               return;
 
        // Check for inset locking
        if (bv_->theLockingInset()) {
@@ -553,31 +449,49 @@ void BufferView::Pimpl::workAreaMotionNotify(int x, int y, unsigned int state)
                                                  cursor.par(), cursor.pos());
                int width = bv_->theLockingInset()->width(bv_, font);
                int inset_x = font.isVisibleRightToLeft()
-                       ? cursor.x() - width : cursor.x();
+                       ? cursor.ix() - width : cursor.ix();
                int start_x = inset_x + bv_->theLockingInset()->scroll();
+
                bv_->theLockingInset()->
                        insetMotionNotify(bv_,
                                          x - start_x,
-                                         y - cursor.y() + bv_->text->first_y,
+                                         y - cursor.iy() + bv_->text->first_y,
                                          state);
                return;
        }
-   
+
        /* The test for not selection possible is needed, that only motion
           events are used, where the bottom press event was on
           the drawing area too */
        if (!selection_possible)
                return;
-       screen_->hideCursor();
 
+       screen().hideCursor();
+
+       Row * cursorrow = bv_->text->cursor.row();
        bv_->text->setCursorFromCoordinates(bv_, x, y + bv_->text->first_y);
-      
+#if 0
+       // sorry for this but I have a strange error that the y value jumps at
+       // a certain point. This seems like an error in my xforms library or
+       // in some other local environment, but I would like to leave this here
+       // for the moment until I can remove this (Jug 20020418)
+       if (y_before < bv_->text->cursor.y())
+               lyxerr << y_before << ":" << bv_->text->cursor.y() << endl;
+#endif
+       // This is to allow jumping over large insets
+       if (cursorrow == bv_->text->cursor.row()) {
+               if (y >= int(workarea().workHeight())) {
+                       bv_->text->cursorDown(bv_, false);
+               } else if (y < 0) {
+                       bv_->text->cursorUp(bv_, false);
+               }
+       }
+
        if (!bv_->text->selection.set())
                update(bv_->text, BufferView::UPDATE); // Maybe an empty line was deleted
-      
+
        bv_->text->setSelection(bv_);
-       screen_->toggleToggle(bv_->text, bv_);
+       screen().toggleToggle(bv_->text, bv_);
        fitCursor();
        showCursor();
 }
@@ -585,59 +499,65 @@ void BufferView::Pimpl::workAreaMotionNotify(int x, int y, unsigned int state)
 
 // Single-click on work area
 void BufferView::Pimpl::workAreaButtonPress(int xpos, int ypos,
-                                            unsigned int button)
+                                           mouse_button::state button)
 {
-       if (!buffer_ || !screen_.get()) return;
+       if (!buffer_)
+               return;
+
+       // ok ok, this is a hack (for xforms)
+       if (button == mouse_button::button4) {
+               scroll(-lyxrc.wheel_jump);
+               // We shouldn't go further down as we really should only do the
+               // scrolling and be done with this. Otherwise we may open some
+               // dialogs (Jug 20020424).
+               return;
+       } else if (button == mouse_button::button5) {
+               scroll(lyxrc.wheel_jump);
+               // We shouldn't go further down as we really should only do the
+               // scrolling and be done with this. Otherwise we may open some
+               // dialogs (Jug 20020424).
+               return;
+       }
 
        Inset * inset_hit = checkInsetHit(bv_->text, xpos, ypos);
 
-       // ok ok, this is a hack.
-       if (button == 4 || button == 5) {
-               switch (button) {
-               case 4:
-                       scrollUp(lyxrc.wheel_jump); // default 100, set in lyxrc
-                       break;
-               case 5:
-                       scrollDown(lyxrc.wheel_jump);
-                       break;
-               }
+       // Middle button press pastes if we have a selection
+       // We do this here as if the selection was inside an inset
+       // it could get cleared on the unlocking of the inset so
+       // we have to check this first
+       bool paste_internally = false;
+       if (button == mouse_button::button2 && bv_->getLyXText()->selection.set()) {
+               owner_->getLyXFunc()->dispatch(LFUN_COPY);
+               paste_internally = true;
        }
-       
+
+       int const screen_first = bv_->text->first_y;
+
        if (bv_->theLockingInset()) {
                // We are in inset locking mode
-               
+
                /* Check whether the inset was hit. If not reset mode,
                   otherwise give the event to the inset */
                if (inset_hit == bv_->theLockingInset()) {
                        bv_->theLockingInset()->
-                               insetButtonPress(bv_,xpos, ypos,button);
+                               insetButtonPress(bv_, xpos, ypos, button);
                        return;
                } else {
                        bv_->unlockInset(bv_->theLockingInset());
                }
        }
-       
+
        if (!inset_hit)
                selection_possible = true;
-       screen_->hideCursor();
+       screen().hideCursor();
 
-       int const screen_first = bv_->text->first_y;
-       
-       // Middle button press pastes if we have a selection
-       bool paste_internally = false;
-       if (button == 2
-           && bv_->text->selection.set()) {
-               owner_->getLyXFunc()->dispatch(LFUN_COPY);
-               paste_internally = true;
-       }
-       
        // Clear the selection
-       screen_->toggleSelection(bv_->text, bv_);
+       screen().toggleSelection(bv_->text, bv_);
        bv_->text->clearSelection();
        bv_->text->fullRebreak(bv_);
        update();
        updateScrollbar();
-       
+
        // Single left click in math inset?
        if (isHighlyEditableInset(inset_hit)) {
                // Highly editable inset, like math
@@ -645,34 +565,38 @@ void BufferView::Pimpl::workAreaButtonPress(int xpos, int ypos,
                selection_possible = false;
                owner_->updateLayoutChoice();
                owner_->message(inset->editMessage());
-               // IMO the inset has to be first in edit-mode and then we send the
-               // button press. (Jug 20020222)
-               inset->edit(bv_); //, xpos, ypos, button);
+               //inset->edit(bv_, xpos, ypos, button);
+               // We just have to lock the inset before calling a PressEvent on it!
+               // we don't need the edit() call here! (Jug20020329)
+               if (!bv_->lockInset(inset)) {
+                       lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
+               }
                inset->insetButtonPress(bv_, xpos, ypos, button);
                return;
-       } 
-       
+       }
+       // I'm not sure we should continue here if we hit an inset (Jug20020403)
+
        // Right click on a footnote flag opens float menu
-       if (button == 3) { 
+       if (button == mouse_button::button3) {
                selection_possible = false;
                return;
        }
-       
+
        if (!inset_hit) // otherwise it was already set in checkInsetHit(...)
                bv_->text->setCursorFromCoordinates(bv_, xpos, ypos + screen_first);
        finishUndo();
        bv_->text->selection.cursor = bv_->text->cursor;
        bv_->text->cursor.x_fix(bv_->text->cursor.x());
-       
+
        owner_->updateLayoutChoice();
        if (fitCursor()) {
                selection_possible = false;
        }
-       
+
        // Insert primary selection with middle mouse
        // if there is a local selection in the current buffer,
        // insert this
-       if (button == 2) {
+       if (button == mouse_button::button2) {
                if (paste_internally)
                        owner_->getLyXFunc()->dispatch(LFUN_PASTE);
                else
@@ -684,9 +608,8 @@ void BufferView::Pimpl::workAreaButtonPress(int xpos, int ypos,
 }
 
 
-void BufferView::Pimpl::doubleClick(int /*x*/, int /*y*/, unsigned int button) 
+void BufferView::Pimpl::doubleClick(int /*x*/, int /*y*/, mouse_button::state button)
 {
-       // select a word
        if (!buffer_)
                return;
 
@@ -695,12 +618,12 @@ void BufferView::Pimpl::doubleClick(int /*x*/, int /*y*/, unsigned int button)
        if (text->bv_owner && bv_->theLockingInset())
                return;
 
-       if (screen_.get() && button == 1) {
+       if (button == mouse_button::button1) {
                if (text->bv_owner) {
-                       screen_->hideCursor();
-                       screen_->toggleSelection(text, bv_);
+                       screen().hideCursor();
+                       screen().toggleSelection(text, bv_);
                        text->selectWord(bv_, LyXText::WHOLE_WORD_STRICT);
-                       screen_->toggleSelection(text, bv_, false);
+                       screen().toggleSelection(text, bv_, false);
                } else {
                        text->selectWord(bv_, LyXText::WHOLE_WORD_STRICT);
                }
@@ -711,9 +634,8 @@ void BufferView::Pimpl::doubleClick(int /*x*/, int /*y*/, unsigned int button)
 }
 
 
-void BufferView::Pimpl::tripleClick(int /*x*/, int /*y*/, unsigned int button)
+void BufferView::Pimpl::tripleClick(int /*x*/, int /*y*/, mouse_button::state button)
 {
-       // select a line
        if (!buffer_)
                return;
 
@@ -722,17 +644,17 @@ void BufferView::Pimpl::tripleClick(int /*x*/, int /*y*/, unsigned int button)
        if (text->bv_owner && bv_->theLockingInset())
            return;
 
-       if (screen_.get() && (button == 1)) {
+       if (button == mouse_button::button1) {
                if (text->bv_owner) {
-                       screen_->hideCursor();
-                       screen_->toggleSelection(text, bv_);
+                       screen().hideCursor();
+                       screen().toggleSelection(text, bv_);
                }
                text->cursorHome(bv_);
                text->selection.cursor = text->cursor;
                text->cursorEnd(bv_);
                text->setSelection(bv_);
                if (text->bv_owner) {
-                       screen_->toggleSelection(text, bv_, false);
+                       screen().toggleSelection(text, bv_, false);
                }
                /* This will fit the cursor on the screen
                 * if necessary */
@@ -743,50 +665,48 @@ void BufferView::Pimpl::tripleClick(int /*x*/, int /*y*/, unsigned int button)
 
 void BufferView::Pimpl::selectionRequested()
 {
+       static string sel;
+
        if (!available())
                return;
-       string const sel(bv_->getLyXText()->selectionAsString(bv_->buffer(),
-                                                             false)); 
+
+       LyXText * text = bv_->getLyXText();
+
+       if (text->selection.set() &&
+               (!bv_->text->xsel_cache.set() ||
+                text->selection.start != bv_->text->xsel_cache.start ||
+                text->selection.end != bv_->text->xsel_cache.end))
+       {
+               bv_->text->xsel_cache = text->selection;
+               sel = text->selectionAsString(bv_->buffer(), false);
+       } else if (!text->selection.set()) {
+               sel = string();
+               bv_->text->xsel_cache.set(false);
+       }
        if (!sel.empty()) {
-               workarea_.putClipboard(sel);
+               workarea().putClipboard(sel);
        }
 }
 
+
 void BufferView::Pimpl::selectionLost()
 {
-       if (active() && available()) { 
+       if (available()) {
                hideCursor();
                toggleSelection();
                bv_->getLyXText()->clearSelection();
-               showCursor(); 
-       }
-}
-
-void BufferView::Pimpl::enterView()
-{
-       if (active() && available()) {
-               SetXtermCursor(workarea_.getWin());
-               using_xterm_cursor = true;
-       }
-}
-
-
-void BufferView::Pimpl::leaveView()
-{
-       if (using_xterm_cursor) {
-               XUndefineCursor(fl_get_display(), workarea_.getWin());
-               using_xterm_cursor = false;
+               showCursor();
+               bv_->text->xsel_cache.set(false);
        }
 }
 
 
 void BufferView::Pimpl::workAreaButtonRelease(int x, int y,
-                                             unsigned int button)
+                                             mouse_button::state button)
 {
-       if (!buffer_ || !screen_.get()) return;
+       // do nothing if we used the mouse wheel
+       if (!buffer_ || button == mouse_button::button4 || button == mouse_button::button5)
+               return;
 
        // If we hit an inset, we have the inset coordinates in these
        // and inset_hit points to the inset.  If we do not hit an
@@ -797,23 +717,23 @@ void BufferView::Pimpl::workAreaButtonRelease(int x, int y,
                // We are in inset locking mode.
 
                /* LyX does a kind of work-area grabbing for insets.
-                  Only a ButtonPress Event outside the inset will 
+                  Only a ButtonPress Event outside the inset will
                   force a insetUnlock. */
                bv_->theLockingInset()->
                        insetButtonRelease(bv_, x, y, button);
                return;
        }
-       
+
        selection_possible = false;
-       
-       if (button == 2)
+
+       if (button == mouse_button::button2)
                return;
 
        // finish selection
-       if (button == 1) {
-               workarea_.haveSelection(bv_->getLyXText()->selection.set());
+       if (button == mouse_button::button1) {
+               workarea().haveSelection(bv_->getLyXText()->selection.set());
        }
+
        setState();
        owner_->showState();
        owner_->updateMenubar();
@@ -826,7 +746,7 @@ void BufferView::Pimpl::workAreaButtonRelease(int x, int y,
                // if we reach this point with a selection, it
                // must mean we are currently selecting.
                // But we don't want to open the inset
-               // because that is annoying for the user. 
+               // because that is annoying for the user.
                // So just pretend we didn't hit it.
                // this is OK because a "kosher" ButtonRelease
                // will follow a ButtonPress that clears
@@ -835,7 +755,7 @@ void BufferView::Pimpl::workAreaButtonRelease(int x, int y,
                // problems if we end up opening an inset
                if (bv_->getLyXText()->selection.set())
                        return;
+
                // CHECK fix this proper in 0.13
                // well, maybe 13.0 !!!!!!!!!
 
@@ -864,15 +784,19 @@ void BufferView::Pimpl::workAreaButtonRelease(int x, int y,
                        inset->insetButtonRelease(bv_, x, y, button);
                } else {
                        inset_hit->insetButtonRelease(bv_, x, y, button);
+                       // IMO this is a grosshack! Inset's should be changed so that
+                       // they call the actions they have to do with the insetButtonRel.
+                       // function and not in the edit(). This should be changed
+                       // (Jug 20020329)
                        inset_hit->edit(bv_, x, y, button);
                }
                return;
        }
 
        // Maybe we want to edit a bibitem ale970302
-       if (bv_->text->cursor.par()->bibkey && x < 20 + 
+       if (bv_->text->cursor.par()->bibkey && x < 20 +
            bibitemMaxWidth(bv_, textclasslist[buffer_->params.textclass].defaultfont())) {
-               bv_->text->cursor.par()->bibkey->edit(bv_, 0, 0, 0);
+               bv_->text->cursor.par()->bibkey->edit(bv_, 0, 0, mouse_button::none);
        }
 
        return;
@@ -886,23 +810,23 @@ Box BufferView::Pimpl::insetDimensions(LyXText const & text,
        pos_type const pos = cursor.pos();
 
        lyx::Assert(par.getInset(pos));
+
        Inset const & inset(*par.getInset(pos));
 
        LyXFont const & font = text.getFont(buffer_, &par, pos);
+
        int const width = inset.width(bv_, font);
        int const inset_x = font.isVisibleRightToLeft()
-               ? (cursor.x() - width) : cursor.x();
+               ? (cursor.ix() - width) : cursor.ix();
+
        return Box(
                inset_x + inset.scroll(),
                inset_x + width,
-               cursor.y() - inset.ascent(bv_, font),
-               cursor.y() + inset.descent(bv_, font));
+               cursor.iy() - inset.ascent(bv_, font),
+               cursor.iy() + inset.descent(bv_, font));
 }
+
+
 Inset * BufferView::Pimpl::checkInset(LyXText const & text,
                                      LyXCursor const & cursor,
                                      int & x, int & y) const
@@ -915,7 +839,7 @@ Inset * BufferView::Pimpl::checkInset(LyXText const & text,
        }
 
        Inset /*const*/ * inset = par.getInset(pos);
+
        if (!isEditableInset(inset)) {
                return 0;
        }
@@ -923,40 +847,37 @@ Inset * BufferView::Pimpl::checkInset(LyXText const & text,
        Box b(insetDimensions(text, cursor));
 
        if (!b.contained(x, y)) {
-               lyxerr[Debug::GUI] << "Missed inset at x,y " << x << "," << y 
+               lyxerr[Debug::GUI] << "Missed inset at x,y " << x << "," << y
                        << " box " << b << endl;
                return 0;
        }
+
        text.setCursor(bv_, &par, pos, true);
+
        x -= b.x1;
        // The origin of an inset is on the baseline
-       y -= (text.cursor.y());
-  
+       y -= text.cursor.iy();
+
        return inset;
 }
 
+
 Inset * BufferView::Pimpl::checkInsetHit(LyXText * text, int & x, int & y)
 {
-       if (!screen_.get())
-               return 0;
-  
        int y_tmp = y + text->first_y;
+
        LyXCursor cursor;
        text->setCursorFromCoordinates(bv_, cursor, x, y_tmp);
+
        Inset * inset(checkInset(*text, cursor, x, y_tmp));
 
        if (inset) {
                y = y_tmp;
                return inset;
        }
+
        // look at previous position
+
        if (cursor.pos() == 0) {
                return 0;
        }
@@ -972,21 +893,22 @@ Inset * BufferView::Pimpl::checkInsetHit(LyXText * text, int & x, int & y)
 }
 
 
-void BufferView::Pimpl::workAreaExpose()
+void BufferView::Pimpl::workAreaResize()
 {
        static int work_area_width;
-       static unsigned int work_area_height;
+       static int work_area_height;
 
-       bool const widthChange = workarea_.workWidth() != work_area_width;
-       bool const heightChange = workarea_.height() != work_area_height;
+       bool const widthChange = workarea().workWidth() != work_area_width;
+       bool const heightChange = workarea().workHeight() != work_area_height;
 
        // update from work area
-       work_area_width = workarea_.workWidth();
-       work_area_height = workarea_.height();
+       work_area_width = workarea().workWidth();
+       work_area_height = workarea().workHeight();
+
        if (buffer_ != 0) {
                if (widthChange) {
                        // The visible LyXView need a resize
-                       owner_->resize();
+                       resizeCurrentBuffer();
 
                        // Remove all texts from the textcache
                        // This is not _really_ what we want to do. What
@@ -997,21 +919,18 @@ void BufferView::Pimpl::workAreaExpose()
                        if (lyxerr.debugging())
                                textcache.show(lyxerr, "Expose delete all");
                        textcache.clear();
+                       // FIXME: this is aalready done in resizeCurrentBuffer() ??
+                       buffer_->resizeInsets(bv_);
                } else if (heightChange) {
-                       // Rebuild image of current screen
-                       updateScreen();
                        // fitCursor() ensures we don't jump back
                        // to the start of the document on vertical
                        // resize
                        fitCursor();
+               }
+       }
 
-                       // The main window size has changed, repaint most stuff
-                       redraw();
-               } else if (screen_.get())
-                   screen_->redraw(bv_->text, bv_);
-       } else {
-               // Grey box when we don't have a buffer
-               workarea_.greyOut();
+       if (widthChange || heightChange) {
+               repaint();
        }
 
        // always make sure that the scrollbar is sane.
@@ -1023,21 +942,26 @@ void BufferView::Pimpl::workAreaExpose()
 
 void BufferView::Pimpl::update()
 {
-       if (screen_.get() &&
-               (!bv_->theLockingInset() || !bv_->theLockingInset()->nodraw()))
-       {
+       if (!bv_->theLockingInset() || !bv_->theLockingInset()->nodraw()) {
                LyXText::text_status st = bv_->text->status();
-               screen_->update(bv_->text, bv_);
+               screen().update(bv_->text, bv_);
                bool fitc = false;
                while (bv_->text->status() == LyXText::CHANGED_IN_DRAW) {
-                       if (bv_->text->fullRebreak(bv_)) {
-                               st = LyXText::NEED_MORE_REFRESH;
-                               bv_->text->setCursor(bv_, bv_->text->cursor.par(),
-                                                                        bv_->text->cursor.pos());
-                               fitc = true;
+                       bv_->text->fullRebreak(bv_);
+                       st = LyXText::NEED_MORE_REFRESH;
+                       bv_->text->setCursor(bv_, bv_->text->cursor.par(),
+                                            bv_->text->cursor.pos());
+                       if (bv_->text->selection.set()) {
+                               bv_->text->setCursor(bv_, bv_->text->selection.start,
+                                                    bv_->text->selection.start.par(),
+                                                    bv_->text->selection.start.pos());
+                               bv_->text->setCursor(bv_, bv_->text->selection.end,
+                                                    bv_->text->selection.end.par(),
+                                                    bv_->text->selection.end.pos());
                        }
+                       fitc = true;
                        bv_->text->status(bv_, st);
-                       screen_->update(bv_->text, bv_);
+                       screen().update(bv_->text, bv_);
                }
                // do this here instead of in the screen::update because of
                // the above loop!
@@ -1051,7 +975,7 @@ void BufferView::Pimpl::update()
 // -3 - update
 // -2 - update, move sel_cursor if selection, fitcursor
 // -1 - update, move sel_cursor if selection, fitcursor, mark dirty
-//  0 - update, move sel_cursor if selection, fitcursor 
+//  0 - update, move sel_cursor if selection, fitcursor
 //  1 - update, move sel_cursor if selection, fitcursor, mark dirty
 //  3 - update, move sel_cursor if selection
 //
@@ -1071,7 +995,7 @@ void BufferView::Pimpl::update()
 //       UPDATE = 0,
 //       SELECT = 1,
 //       FITCUR = 2,
-//       CHANGE = 4 
+//       CHANGE = 4
 // };
 //
 // UPDATE_ONLY = UPDATE;
@@ -1097,11 +1021,11 @@ void BufferView::Pimpl::update(LyXText * text, BufferView::UpdateCodes f)
 
        if (text->inset_owner) {
                text->inset_owner->setUpdateStatus(bv_, InsetText::NONE);
-           updateInset(text->inset_owner, false);
+               updateInset(text->inset_owner, false);
        } else {
-           update();
+               update();
        }
-               
+
        if ((f & FITCUR)) {
                fitCursor();
        }
@@ -1119,72 +1043,124 @@ void BufferView::Pimpl::cursorToggle()
                cursor_timeout.restart();
                return;
        }
-       if (!screen_.get()) {
-               cursor_timeout.restart();
-               return;
-       }
 
        /* FIXME */
        extern void reapSpellchecker(void);
        reapSpellchecker();
-        
+
        if (!bv_->theLockingInset()) {
-               screen_->cursorToggle(bv_);
+               screen().cursorToggle(bv_);
        } else {
                bv_->theLockingInset()->toggleInsetCursor(bv_);
        }
-       
+
        cursor_timeout.restart();
 }
 
 
 void BufferView::Pimpl::cursorPrevious(LyXText * text)
 {
-       if (!text->cursor.row()->previous())
+       if (!text->cursor.row()->previous()) {
+               if (text->first_y > 0) {
+                       int new_y = bv_->text->first_y - workarea().workHeight();
+                       screen().draw(bv_->text, bv_, new_y < 0 ? 0 : new_y);
+                       updateScrollbar();
+               }
                return;
-       
+       }
+
        int y = text->first_y;
        Row * cursorrow = text->cursor.row();
-       
-       text->setCursorFromCoordinates(bv_, bv_->text->cursor.x_fix(), y);
+
+       text->setCursorFromCoordinates(bv_, text->cursor.x_fix(), y);
        finishUndo();
-       // This is to allow jumping over large insets
-       if ((cursorrow == text->cursor.row()))
-               text->cursorUp(bv_);
-       
-       if (text->inset_owner ||
-           text->cursor.row()->height() < workarea_.height())
-               screen_->draw(bv_->text, bv_,
-                             text->cursor.y()
-                             - text->cursor.row()->baseline()
-                             + text->cursor.row()->height()
-                             - workarea_.height() + 1);
+
+       int new_y;
+       if (cursorrow == bv_->text->cursor.row()) {
+               // we have a row which is higher than the workarea so we leave the
+               // cursor on the start of the row and move only the draw up as soon
+               // as we move the cursor or do something while inside the row (it may
+               // span several workarea-heights) we'll move to the top again, but this
+               // is better than just jump down and only display part of the row.
+               new_y = bv_->text->first_y - workarea().workHeight();
+       } else {
+               if (text->inset_owner) {
+                       new_y = bv_->text->cursor.iy()
+                               + bv_->theLockingInset()->insetInInsetY() + y
+                               + text->cursor.row()->height()
+                               - workarea().workHeight() + 1;
+               } else {
+                       new_y = text->cursor.y()
+                               - text->cursor.row()->baseline()
+                               + text->cursor.row()->height()
+                               - workarea().workHeight() + 1;
+               }
+       }
+       screen().draw(bv_->text, bv_,  new_y < 0 ? 0 : new_y);
+       if (text->cursor.row()->previous()) {
+               LyXCursor cur;
+               text->setCursor(bv_, cur, text->cursor.row()->previous()->par(),
+                                               text->cursor.row()->previous()->pos(), false);
+               if (cur.y() > text->first_y) {
+                       text->cursorUp(bv_, true);
+               }
+       }
        updateScrollbar();
 }
 
 
 void BufferView::Pimpl::cursorNext(LyXText * text)
 {
-       if (!text->cursor.row()->next())
+       if (!text->cursor.row()->next()) {
+               int y = text->cursor.y() - text->cursor.row()->baseline() +
+                       text->cursor.row()->height();
+               if (y > int(text->first_y + workarea().workHeight())) {
+                       screen().draw(bv_->text, bv_,
+                                                 bv_->text->first_y + workarea().workHeight());
+                       updateScrollbar();
+               }
                return;
-       
-       int y = text->first_y + workarea_.height();
-//     if (text->inset_owner)
-//             y += bv_->text->first;
+       }
+
+       int y = text->first_y + workarea().workHeight();
+       if (text->inset_owner && !text->first_y) {
+               y -= (bv_->text->cursor.iy()
+                         - bv_->text->first_y
+                         + bv_->theLockingInset()->insetInInsetY());
+       }
+
        text->getRowNearY(y);
-    
+
        Row * cursorrow = text->cursor.row();
-       text->setCursorFromCoordinates(bv_, text->cursor.x_fix(), y); // + workarea_->height());
+       text->setCursorFromCoordinates(bv_, text->cursor.x_fix(), y); // + workarea().workHeight());
        finishUndo();
-       // This is to allow jumping over large insets
-       if ((cursorrow == bv_->text->cursor.row()))
-               text->cursorDown(bv_);
-       
-       if (text->inset_owner ||
-           text->cursor.row()->height() < workarea_.height())
-               screen_->draw(bv_->text, bv_, text->cursor.y() -
-                             text->cursor.row()->baseline());
+
+       int new_y;
+       if (cursorrow == bv_->text->cursor.row()) {
+               // we have a row which is higher than the workarea so we leave the
+               // cursor on the start of the row and move only the draw down as soon
+               // as we move the cursor or do something while inside the row (it may
+               // span several workarea-heights) we'll move to the top again, but this
+               // is better than just jump down and only display part of the row.
+               new_y = bv_->text->first_y + workarea().workHeight();
+       } else {
+               if (text->inset_owner) {
+                       new_y = bv_->text->cursor.iy()
+                               + bv_->theLockingInset()->insetInInsetY()
+                               + y - text->cursor.row()->baseline();
+               } else {
+                       new_y =  text->cursor.y() - text->cursor.row()->baseline();
+               }
+       }
+       screen().draw(bv_->text, bv_, new_y);
+       if (text->cursor.row()->next()) {
+               LyXCursor cur;
+               text->setCursor(bv_, cur, text->cursor.row()->next()->par(),
+                                               text->cursor.row()->next()->pos(), false);
+               if (cur.y() < int(text->first_y + workarea().workHeight())) {
+                       text->cursorDown(bv_, true);
+               }
+       }
        updateScrollbar();
 }
 
@@ -1230,7 +1206,7 @@ void BufferView::Pimpl::restorePosition(unsigned int i)
 
        if (fname != buffer_->fileName()) {
                Buffer * b = bufferlist.exists(fname) ?
-                       bufferlist.getBuffer(fname) :
+                       bufferlist.getBuffer(fname) :
                        bufferlist.loadLyXFile(fname); // don't ask, just load it
                if (b != 0) buffer(b);
        }
@@ -1242,7 +1218,7 @@ void BufferView::Pimpl::restorePosition(unsigned int i)
        bv_->text->setCursor(bv_, par,
                             min(par->size(), saved_positions[i].par_pos));
 
-       update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
+       update(bv_->text, BufferView::SELECT | BufferView::FITCUR);
        if (i > 0) {
                ostringstream str;
                str << _("Moved to bookmark") << ' ' << i;
@@ -1266,7 +1242,10 @@ void BufferView::Pimpl::setState()
                return;
 
        LyXText * text = bv_->getLyXText();
-       if (text->real_current_font.isRightToLeft()) {
+       if (text->real_current_font.isRightToLeft()
+           && !(bv_->theLockingInset()
+                && bv_->theLockingInset()->lyxCode()== Inset::ERT_CODE))
+       {
                if (owner_->getIntl()->keymap == Intl::PRIMARY)
                        owner_->getIntl()->KeyMapSec();
        } else {
@@ -1276,136 +1255,99 @@ void BufferView::Pimpl::setState()
 }
 
 
-void BufferView::Pimpl::insetSleep()
-{
-       if (bv_->theLockingInset() && !inset_slept) {
-               bv_->theLockingInset()->getCursorPos(bv_, bv_->slx, bv_->sly);
-               bv_->theLockingInset()->insetUnlock(bv_);
-               inset_slept = true;
-       }
-}
-
-
-void BufferView::Pimpl::insetWakeup()
-{
-       if (bv_->theLockingInset() && inset_slept) {
-               bv_->theLockingInset()->edit(bv_, bv_->slx, bv_->sly, 0);
-               inset_slept = false;
-       }
-}
-
-
 void BufferView::Pimpl::insetUnlock()
 {
        if (bv_->theLockingInset()) {
-               if (!inset_slept)
-                       bv_->theLockingInset()->insetUnlock(bv_);
+               bv_->theLockingInset()->insetUnlock(bv_);
                bv_->theLockingInset(0);
                finishUndo();
-               inset_slept = false;
        }
 }
 
 
-bool BufferView::Pimpl::focus() const
-{
-       return workarea_.hasFocus();
-}
-
-
-void BufferView::Pimpl::focus(bool f)
-{
-       if (f) workarea_.setFocus();
-}
-
-
-bool BufferView::Pimpl::active() const
-{
-       return workarea_.active();
-}
-
-
-bool BufferView::Pimpl::belowMouse() const 
-{
-       return workarea_.belowMouse();
-}
-
-
 void BufferView::Pimpl::showCursor()
 {
-       if (screen_.get()) {
-               if (bv_->theLockingInset())
-                       bv_->theLockingInset()->showInsetCursor(bv_);
-               else
-                       screen_->showCursor(bv_->text, bv_);
-       }
+       if (bv_->theLockingInset())
+               bv_->theLockingInset()->showInsetCursor(bv_);
+       else
+               screen().showCursor(bv_->text, bv_);
 }
 
 
 void BufferView::Pimpl::hideCursor()
 {
-       if (screen_.get()) {
-               if (!bv_->theLockingInset())
-//                     bv_->theLockingInset()->hideInsetCursor(bv_);
-//             else
-                       screen_->hideCursor();
-       }
+       if (!bv_->theLockingInset())
+               screen().hideCursor();
 }
 
 
 void BufferView::Pimpl::toggleSelection(bool b)
 {
-       if (screen_.get()) {
-               if (bv_->theLockingInset())
-                       bv_->theLockingInset()->toggleSelection(bv_, b);
-               screen_->toggleSelection(bv_->text, bv_, b);
-       }
+       if (bv_->theLockingInset())
+               bv_->theLockingInset()->toggleSelection(bv_, b);
+       screen().toggleSelection(bv_->text, bv_, b);
 }
 
 
 void BufferView::Pimpl::toggleToggle()
 {
-       if (screen_.get())
-               screen_->toggleToggle(bv_->text, bv_);
+       screen().toggleToggle(bv_->text, bv_);
 }
 
 
-void BufferView::Pimpl::center() 
+void BufferView::Pimpl::center()
 {
-       beforeChange(bv_->text);
-       if (bv_->text->cursor.y() > static_cast<int>((workarea_.height() / 2))) {
-               screen_->draw(bv_->text, bv_, bv_->text->cursor.y() - workarea_.height() / 2);
-       } else {
-               screen_->draw(bv_->text, bv_, 0);
+       LyXText * t = bv_->text;
+       beforeChange(t);
+       int const half_height = workarea().workHeight() / 2;
+       int new_y = 0;
+       if (t->cursor.y() > half_height) {
+               new_y = t->cursor.y() - half_height;
        }
-       update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
-       redraw();
+       // FIXME: can we do this w/o calling screen directly ?
+       // This updates first_y but means the fitCursor() call
+       // from the update(FITCUR) doesn't realise that we might
+       // have moved (e.g. from GOTOPARAGRAPH), so doesn't cause
+       // the scrollbar to be updated as it should, so we have
+       // to do it manually. Any operation that does a center()
+       // and also might have moved first_y must make sure to call
+       // updateScrollbar() currently. Never mind that this is a 
+       // pretty obfuscated way of updating t->first_y
+       screen().draw(t, bv_, new_y);
+       update(t, BufferView::SELECT | BufferView::FITCUR);
 }
 
 
-void BufferView::Pimpl::pasteClipboard(bool asPara) 
+void BufferView::Pimpl::pasteClipboard(bool asPara)
 {
-       if (!buffer_) return;
+       if (!buffer_)
+               return;
 
-       screen_->hideCursor();
+       screen().hideCursor();
        beforeChange(bv_->text);
-       
-       string const clip(workarea_.getClipboard());
-       
-       if (clip.empty()) return;
+
+       string const clip(workarea().getClipboard());
+
+       if (clip.empty())
+               return;
 
        if (asPara) {
                bv_->getLyXText()->insertStringAsParagraphs(bv_, clip);
        } else {
                bv_->getLyXText()->insertStringAsLines(bv_, clip);
        }
+       bv_->getLyXText()->clearSelection();
        update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
 }
 
 
 void BufferView::Pimpl::stuffClipboard(string const & stuff) const
 {
-       workarea_.putClipboard(stuff);
+       workarea().putClipboard(stuff);
 }
 
 
@@ -1416,18 +1358,32 @@ void BufferView::Pimpl::stuffClipboard(string const & stuff) const
 
 
 inline
-void BufferView::Pimpl::moveCursorUpdate(bool selecting)
+void BufferView::Pimpl::moveCursorUpdate(bool selecting, bool fitcur)
 {
        LyXText * lt = bv_->getLyXText();
-       
+
        if (selecting || lt->selection.mark()) {
                lt->setSelection(bv_);
                if (lt->bv_owner)
                        toggleToggle();
+               else
+                       updateInset(lt->inset_owner, false);
        }
-       update(lt, BufferView::SELECT|BufferView::FITCUR);
-       showCursor();
-       
+       if (lt->bv_owner) {
+               if (fitcur)
+                       update(lt, BufferView::SELECT|BufferView::FITCUR);
+               else
+                       update(lt, BufferView::SELECT);
+               showCursor();
+       } else if (bv_->text->status() != LyXText::UNCHANGED) {
+               bv_->theLockingInset()->hideInsetCursor(bv_);
+               update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
+               showCursor();
+       }
+
+       if (!lt->selection.set())
+               workarea().haveSelection(false);
+
        /* ---> Everytime the cursor is moved, show the current font state. */
        // should this too me moved out of this func?
        //owner->showState();
@@ -1473,7 +1429,7 @@ void BufferView::Pimpl::MenuInsertLyXFile(string const & filen)
                FileDialog::Result result =
                        fileDlg.Select(initpath,
                                       _("*.lyx| LyX Documents (*.lyx)"));
+
                if (result.first == FileDialog::Later)
                        return;
 
@@ -1491,7 +1447,7 @@ void BufferView::Pimpl::MenuInsertLyXFile(string const & filen)
        filename = FileSearch(string(), filename, "lyx");
 
        string const disp_fn(MakeDisplayPath(filename));
-       
+
        ostringstream s1;
        s1 << _("Inserting document") << ' '
           << disp_fn << " ...";
@@ -1515,7 +1471,9 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
 {
        lyxerr[Debug::ACTION] << "BufferView::Pimpl::Dispatch: action["
                              << action <<"] arg[" << argument << "]" << endl;
-       
+
+       LyXTextClass const & tclass = textclasslist[buffer_->params.textclass];
+
        switch (action) {
                // --- Misc -------------------------------------------
        case LFUN_APPENDIX:
@@ -1536,11 +1494,11 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                InsetCommandParams p;
                p.setCmdName("tableofcontents");
                Inset * inset = new InsetTOC(p);
-               if (!insertInset(inset, "Standard"))
+               if (!insertInset(inset, tclass.defaultLayoutName()))
                        delete inset;
                break;
        }
-               
+
        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)
@@ -1559,42 +1517,42 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                }
                break;
        }
-               
+
        case LFUN_PASTE:
                bv_->paste();
                setState();
                break;
-               
+
        case LFUN_PASTESELECTION:
        {
-               bool asPara = false;
+               bool asPara = false;
                if (argument == "paragraph")
                        asPara = true;
                pasteClipboard(asPara);
        }
        break;
-       
+
        case LFUN_CUT:
                bv_->cut();
                break;
-               
+
        case LFUN_COPY:
                bv_->copy();
                break;
-               
+
        case LFUN_LAYOUT_COPY:
                bv_->copyEnvironment();
                break;
-               
+
        case LFUN_LAYOUT_PASTE:
                bv_->pasteEnvironment();
                setState();
                break;
-               
+
        case LFUN_GOTOERROR:
                gotoInset(Inset::ERROR_CODE, false);
                break;
-               
+
        case LFUN_GOTONOTE:
                gotoInset(Inset::IGNORE_CODE, false);
                break;
@@ -1611,15 +1569,15 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
        case LFUN_HYPHENATION:
                specialChar(InsetSpecialChar::HYPHENATION);
                break;
-               
+
        case LFUN_LIGATURE_BREAK:
                specialChar(InsetSpecialChar::LIGATURE_BREAK);
                break;
-               
+
        case LFUN_LDOTS:
                specialChar(InsetSpecialChar::LDOTS);
                break;
-               
+
        case LFUN_END_OF_SENTENCE:
                specialChar(InsetSpecialChar::END_OF_SENTENCE);
                break;
@@ -1627,23 +1585,19 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
        case LFUN_MENU_SEPARATOR:
                specialChar(InsetSpecialChar::MENU_SEPARATOR);
                break;
-               
+
        case LFUN_HFILL:
                hfill();
                break;
-               
-       case LFUN_DEPTH:
-               changeDepth(bv_, bv_->getLyXText(), 0);
-               break;
-               
+
        case LFUN_DEPTH_MIN:
                changeDepth(bv_, bv_->getLyXText(), -1);
                break;
-               
+
        case LFUN_DEPTH_PLUS:
                changeDepth(bv_, bv_->getLyXText(), 1);
                break;
-               
+
        case LFUN_FREE:
                owner_->getDialogs()->setUserFreeFont();
                break;
@@ -1651,7 +1605,7 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
        case LFUN_FILE_INSERT:
                MenuInsertLyXFile(argument);
                break;
-       
+
        case LFUN_FILE_INSERT_ASCII_PARA:
                InsertAsciiFile(bv_, argument, true);
                break;
@@ -1659,24 +1613,32 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
        case LFUN_FILE_INSERT_ASCII:
                InsertAsciiFile(bv_, argument, false);
                break;
-               
+
        case LFUN_LAYOUT:
        {
                lyxerr[Debug::INFO] << "LFUN_LAYOUT: (arg) "
                                    << argument << endl;
-               
+
+               // This is not the good solution to the empty argument
+               // problem, but it will hopefully suffice for 1.2.0.
+               // The correct solution would be to augument the
+               // function list/array with information about what
+               // functions needs arguments and their type.
+               if (argument.empty()) {
+                       owner_->getLyXFunc()->setErrorMessage(
+                               _("LyX function 'layout' needs an argument."));
+                       break;
+               }
+
                // Derive layout number from given argument (string)
-               // and current buffer's textclass (number). */    
-               textclass_type tclass = buffer_->params.textclass;
-               bool hasLayout =
-                       textclasslist[tclass].hasLayout(argument);
+               // and current buffer's textclass (number). */
+               bool hasLayout = tclass.hasLayout(argument);
                string layout = argument;
 
                // If the entry is obsolete, use the new one instead.
                if (hasLayout) {
-                       string const & obs = textclasslist[tclass][layout]
-                               .obsoleted_by();
-                       if (!obs.empty()) 
+                       string const & obs = tclass[layout]->obsoleted_by();
+                       if (!obs.empty())
                                layout = obs;
                }
 
@@ -1687,8 +1649,21 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                        break;
                }
 
-               if (current_layout != layout) {
-                       LyXText * lt = bv_->getLyXText();
+               bool change_layout = (current_layout != layout);
+               LyXText * lt = bv_->getLyXText();
+               if (!change_layout && lt->selection.set() &&
+                       lt->selection.start.par() != lt->selection.end.par())
+               {
+                       Paragraph * spar = lt->selection.start.par();
+                       Paragraph * epar = lt->selection.end.par()->next();
+                       while(spar != epar) {
+                               if (spar->layout()->name() != current_layout) {
+                                       change_layout = true;
+                                       break;
+                               }
+                       }
+               }
+               if (change_layout) {
                        hideCursor();
                        current_layout = layout;
                        update(lt,
@@ -1720,50 +1695,50 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                bold(bv_);
                owner_->showState();
                break;
-               
+
        case LFUN_NOUN:
                noun(bv_);
                owner_->showState();
                break;
-               
+
        case LFUN_CODE:
                code(bv_);
                owner_->showState();
                break;
-               
+
        case LFUN_SANS:
                sans(bv_);
                owner_->showState();
                break;
-               
+
        case LFUN_ROMAN:
                roman(bv_);
                owner_->showState();
                break;
-               
+
        case LFUN_DEFAULT:
                styleReset(bv_);
                owner_->showState();
                break;
-               
+
        case LFUN_UNDERLINE:
                underline(bv_);
                owner_->showState();
                break;
-               
+
        case LFUN_FONT_SIZE:
                fontSize(bv_, argument);
                owner_->showState();
                break;
-               
+
        case LFUN_FONT_STATE:
                owner_->getLyXFunc()->setMessage(currentState(bv_));
                break;
-               
+
        case LFUN_UPCASE_WORD:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                update(lt,
                       BufferView::SELECT
                       | BufferView::FITCUR);
@@ -1776,11 +1751,11 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                       | BufferView::CHANGE);
        }
        break;
-               
+
        case LFUN_LOWCASE_WORD:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                update(lt, BufferView::SELECT|BufferView::FITCUR);
                lt->changeCase(bv_, LyXText::text_lowercase);
                if (lt->inset_owner)
@@ -1791,11 +1766,11 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                       | BufferView::CHANGE);
        }
        break;
-               
+
        case LFUN_CAPITALIZE_WORD:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                update(lt, BufferView::SELECT|BufferView::FITCUR);
                lt->changeCase(bv_, LyXText::text_capitalization);
                if (lt->inset_owner)
@@ -1810,7 +1785,7 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
        case LFUN_TRANSPOSE_CHARS:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                update(lt, BufferView::SELECT|BufferView::FITCUR);
                lt->transposeChars(*bv_);
                if (lt->inset_owner)
@@ -1821,8 +1796,8 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                       | BufferView::CHANGE);
        }
        break;
-               
-                                         
+
+
        case LFUN_INSERT_LABEL:
                MenuInsertLabel(bv_, argument);
                break;
@@ -1855,29 +1830,29 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
        {
                string label(argument);
                if (label.empty()) {
-                       InsetRef * inset = 
+                       InsetRef * inset =
                                static_cast<InsetRef*>(getInsetByCode(Inset::REF_CODE));
                        if (inset) {
-                                label = inset->getContents();
+                               label = inset->getContents();
                                savePosition(0);
                        }
                }
-               
+
                if (!label.empty()) {
                        //bv_->savePosition(0);
                        if (!bv_->gotoLabel(label))
-                               Alert::alert(_("Error"), 
-                                          _("Couldn't find this label"), 
+                               Alert::alert(_("Error"),
+                                          _("Couldn't find this label"),
                                           _("in current document."));
                }
        }
        break;
-               
+
                // --- Cursor Movements -----------------------------
        case LFUN_RIGHT:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                bool is_rtl = lt->cursor.par()->isRightToLeftPar(buffer_->params);
                if (!lt->selection.mark())
                        beforeChange(lt);
@@ -1902,13 +1877,13 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                owner_->showState();
        }
        break;
-               
+
        case LFUN_LEFT:
        {
                // This is soooo ugly. Isn`t it possible to make
                // it simpler? (Lgb)
                LyXText * lt = bv_->getLyXText();
-               bool is_rtl = lt->cursor.par()->isRightToLeftPar(buffer_->params);
+               bool const is_rtl = lt->cursor.par()->isRightToLeftPar(buffer_->params);
                if (!lt->selection.mark())
                        beforeChange(lt);
                update(lt, BufferView::SELECT|BufferView::FITCUR);
@@ -1935,11 +1910,11 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                owner_->showState();
        }
        break;
-               
+
        case LFUN_UP:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                if (!lt->selection.mark())
                        beforeChange(lt);
                update(lt, BufferView::UPDATE);
@@ -1949,11 +1924,11 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                owner_->showState();
        }
        break;
-               
+
        case LFUN_DOWN:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                if (!lt->selection.mark())
                        beforeChange(lt);
                update(lt, BufferView::UPDATE);
@@ -1967,7 +1942,7 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
        case LFUN_UP_PARAGRAPH:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                if (!lt->selection.mark())
                        beforeChange(lt);
                update(lt, BufferView::UPDATE);
@@ -1977,11 +1952,11 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                owner_->showState();
        }
        break;
-               
+
        case LFUN_DOWN_PARAGRAPH:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                if (!lt->selection.mark())
                        beforeChange(lt);
                update(lt, BufferView::UPDATE);
@@ -1991,39 +1966,39 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                owner_->showState();
        }
        break;
-               
+
        case LFUN_PRIOR:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                if (!lt->selection.mark())
                        beforeChange(lt);
                update(lt, BufferView::UPDATE);
                cursorPrevious(lt);
                finishUndo();
-               moveCursorUpdate(false);
+               moveCursorUpdate(false, false);
                owner_->showState();
        }
        break;
-               
+
        case LFUN_NEXT:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                if (!lt->selection.mark())
                        beforeChange(lt);
                update(lt, BufferView::UPDATE);
                cursorNext(lt);
                finishUndo();
-               moveCursorUpdate(false);
+               moveCursorUpdate(false, false);
                owner_->showState();
        }
        break;
-               
+
        case LFUN_HOME:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                if (!lt->selection.mark())
                        beforeChange(lt);
                update(lt, BufferView::SELECT|BufferView::FITCUR);
@@ -2033,11 +2008,11 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                owner_->showState();
        }
        break;
-               
+
        case LFUN_END:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                if (!lt->selection.mark())
                        beforeChange(lt);
                update(lt,
@@ -2048,12 +2023,12 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                owner_->showState();
        }
        break;
-               
+
        case LFUN_SHIFT_TAB:
        case LFUN_TAB:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                if (!lt->selection.mark())
                        beforeChange(lt);
                update(lt,
@@ -2064,11 +2039,11 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                owner_->showState();
        }
        break;
-               
+
        case LFUN_WORDRIGHT:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                if (!lt->selection.mark())
                        beforeChange(lt);
                update(lt, BufferView::SELECT|BufferView::FITCUR);
@@ -2081,11 +2056,11 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                owner_->showState();
        }
        break;
-               
+
        case LFUN_WORDLEFT:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                if (!lt->selection.mark())
                        beforeChange(lt);
                update(lt, BufferView::SELECT|BufferView::FITCUR);
@@ -2098,11 +2073,11 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                owner_->showState();
        }
        break;
-               
+
        case LFUN_BEGINNINGBUF:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                if (!lt->selection.mark())
                        beforeChange(lt);
                update(lt,
@@ -2113,11 +2088,11 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                owner_->showState();
        }
        break;
-               
+
        case LFUN_ENDBUF:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                if (!lt->selection.mark())
                        beforeChange(lt);
                update(lt,
@@ -2128,12 +2103,12 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                owner_->showState();
        }
        break;
-      
+
                /* cursor selection ---------------------------- */
        case LFUN_RIGHTSEL:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                update(lt,
                       BufferView::SELECT|BufferView::FITCUR);
                if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
@@ -2145,11 +2120,11 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                owner_->showState();
        }
        break;
-               
+
        case LFUN_LEFTSEL:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                update(lt,
                       BufferView::SELECT|BufferView::FITCUR);
                if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
@@ -2161,27 +2136,27 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                owner_->showState();
        }
        break;
-               
+
        case LFUN_UPSEL:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                update(lt,
                       BufferView::SELECT|BufferView::FITCUR);
-               lt->cursorUp(bv_);
+               lt->cursorUp(bv_, true);
                finishUndo();
                moveCursorUpdate(true);
                owner_->showState();
        }
        break;
-               
+
        case LFUN_DOWNSEL:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                update(lt,
                       BufferView::SELECT|BufferView::FITCUR);
-               lt->cursorDown(bv_);
+               lt->cursorDown(bv_, true);
                finishUndo();
                moveCursorUpdate(true);
                owner_->showState();
@@ -2191,7 +2166,7 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
        case LFUN_UP_PARAGRAPHSEL:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                update(lt,
                       BufferView::SELECT|BufferView::FITCUR);
                lt->cursorUpParagraph(bv_);
@@ -2200,11 +2175,11 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                owner_->showState();
        }
        break;
-               
+
        case LFUN_DOWN_PARAGRAPHSEL:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                update(lt,
                       BufferView::SELECT|BufferView::FITCUR);
                lt->cursorDownParagraph(bv_);
@@ -2213,11 +2188,11 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                owner_->showState();
        }
        break;
-               
+
        case LFUN_PRIORSEL:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                update(lt, BufferView::SELECT|BufferView::FITCUR);
                cursorPrevious(lt);
                finishUndo();
@@ -2225,11 +2200,11 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                owner_->showState();
        }
        break;
-               
+
        case LFUN_NEXTSEL:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                update(lt, BufferView::SELECT|BufferView::FITCUR);
                cursorNext(lt);
                finishUndo();
@@ -2237,11 +2212,11 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                owner_->showState();
        }
        break;
-               
+
        case LFUN_HOMESEL:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                update(lt, BufferView::SELECT|BufferView::FITCUR);
                lt->cursorHome(bv_);
                finishUndo();
@@ -2249,11 +2224,11 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                owner_->showState();
        }
        break;
-               
+
        case LFUN_ENDSEL:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                update(lt, BufferView::SELECT|BufferView::FITCUR);
                lt->cursorEnd(bv_);
                finishUndo();
@@ -2261,11 +2236,11 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                owner_->showState();
        }
        break;
-               
+
        case LFUN_WORDRIGHTSEL:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                update(lt, BufferView::SELECT|BufferView::FITCUR);
                if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
                        lt->cursorLeftOneWord(bv_);
@@ -2276,11 +2251,11 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                owner_->showState();
        }
        break;
-               
+
        case LFUN_WORDLEFTSEL:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                update(lt, BufferView::SELECT|BufferView::FITCUR);
                if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
                        lt->cursorRightOneWord(bv_);
@@ -2291,11 +2266,11 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                owner_->showState();
        }
        break;
-               
+
        case LFUN_BEGINNINGBUFSEL:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                if (lt->inset_owner)
                        break;
                update(lt, BufferView::SELECT|BufferView::FITCUR);
@@ -2305,11 +2280,11 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                owner_->showState();
        }
        break;
-               
+
        case LFUN_ENDBUFSEL:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                if (lt->inset_owner)
                        break;
                update(lt,
@@ -2332,29 +2307,29 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                       BufferView::SELECT
                       | BufferView::FITCUR
                       | BufferView::CHANGE);
+               lt->setCursor(bv_, lt->cursor.par(), lt->cursor.pos());
                moveCursorUpdate(false);
        }
        break;
-               
+
        case LFUN_PROTECTEDSPACE:
        {
                LyXText * lt = bv_->getLyXText();
+               LyXLayout_ptr const & style = lt->cursor.par()->layout();
 
-               LyXLayout const & style = textclasslist[buffer_->params.textclass][lt->cursor.par()->layout()];
-
-               if (style.free_spacing) {
+               if (style->free_spacing) {
                        lt->insertChar(bv_, ' ');
                        update(lt,
                               BufferView::SELECT
                               | BufferView::FITCUR
                               | BufferView::CHANGE);
                } else {
-                       protectedBlank(lt);
+                       specialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
                }
                moveCursorUpdate(false);
        }
        break;
-               
+
        case LFUN_SETMARK:
        {
                LyXText * lt = bv_->getLyXText();
@@ -2376,7 +2351,7 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                lt->selection.cursor = lt->cursor;
        }
        break;
-               
+
        case LFUN_DELETE:
        {
                LyXText * lt = bv_->getLyXText();
@@ -2405,7 +2380,7 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                LyXText * lt = bv_->getLyXText();
 
                // Reverse the effect of LFUN_BREAKPARAGRAPH_SKIP.
-               
+
                LyXCursor cursor = lt->cursor;
 
                if (!lt->selection.set()) {
@@ -2419,15 +2394,15 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                                                (bv_,
                                                 cursor.par()->params().lineTop(),
                                                 cursor.par()->params().lineBottom(),
-                                                cursor.par()->params().pagebreakTop(), 
+                                                cursor.par()->params().pagebreakTop(),
                                                 cursor.par()->params().pagebreakBottom(),
-                                                VSpace(VSpace::NONE), 
+                                                VSpace(VSpace::NONE),
                                                 cursor.par()->params().spaceBottom(),
-                                                cursor.par()->params().spacing(), 
-                                                cursor.par()->params().align(), 
+                                                cursor.par()->params().spacing(),
+                                                cursor.par()->params().align(),
                                                 cursor.par()->params().labelWidthString(), 0);
                                        lt->cursorLeft(bv_);
-                                       update(lt, 
+                                       update(lt,
                                               BufferView::SELECT
                                               | BufferView::FITCUR
                                               | BufferView::CHANGE);
@@ -2467,7 +2442,7 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
        case LFUN_DELETE_WORD_BACKWARD:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                update(lt, BufferView::SELECT|BufferView::FITCUR);
                lt->deleteWordBackward(bv_);
                update(lt,
@@ -2478,12 +2453,12 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                owner_->showState();
        }
        break;
-               
+
                /* -------> Kill to end of line. */
        case LFUN_DELETE_LINE_FORWARD:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                update(lt, BufferView::SELECT|BufferView::FITCUR);
                lt->deleteLineForward(bv_);
                update(lt,
@@ -2493,12 +2468,12 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                moveCursorUpdate(false);
        }
        break;
-               
+
                /* -------> Set mark off. */
        case LFUN_MARK_OFF:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                beforeChange(lt);
                update(lt, BufferView::SELECT|BufferView::FITCUR);
                lt->selection.cursor = lt->cursor;
@@ -2510,7 +2485,7 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
        case LFUN_MARK_ON:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                beforeChange(lt);
                lt->selection.mark(true);
                update(lt, BufferView::SELECT|BufferView::FITCUR);
@@ -2518,13 +2493,13 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                owner_->getLyXFunc()->setMessage(N_("Mark on"));
        }
        break;
-               
+
        case LFUN_BACKSPACE:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                if (!lt->selection.set()) {
-                       if (owner_->getIntl()->getTrans().backspace()) {
+                       if (owner_->getIntl()->getTransManager().backspace()) {
                                lt->backspace(bv_);
                                lt->selection.cursor = lt->cursor;
                                update(lt,
@@ -2547,22 +2522,22 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
        {
                // Reverse the effect of LFUN_BREAKPARAGRAPH_SKIP.
                LyXText * lt = bv_->getLyXText();
-               
+
                LyXCursor cursor = lt->cursor;
-               
+
                if (!lt->selection.set()) {
-                       if (cursor.pos() == 0 
-                           && !(cursor.par()->params().spaceTop() 
+                       if (cursor.pos() == 0
+                           && !(cursor.par()->params().spaceTop()
                                 == VSpace (VSpace::NONE))) {
-                               lt->setParagraph 
+                               lt->setParagraph
                                        (bv_,
-                                        cursor.par()->params().lineTop(),      
+                                        cursor.par()->params().lineTop(),
                                         cursor.par()->params().lineBottom(),
-                                        cursor.par()->params().pagebreakTop(), 
+                                        cursor.par()->params().pagebreakTop(),
                                         cursor.par()->params().pagebreakBottom(),
                                         VSpace(VSpace::NONE), cursor.par()->params().spaceBottom(),
-                                        cursor.par()->params().spacing(), 
-                                        cursor.par()->params().align(), 
+                                        cursor.par()->params().spacing(),
+                                        cursor.par()->params().align(),
                                         cursor.par()->params().labelWidthString(), 0);
                                update(lt,
                                       BufferView::SELECT
@@ -2584,7 +2559,7 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
        case LFUN_BREAKPARAGRAPH:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                beforeChange(lt);
                lt->breakParagraph(bv_, 0);
                update(lt,
@@ -2600,7 +2575,7 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
        case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                beforeChange(lt);
                lt->breakParagraph(bv_, 1);
                update(lt,
@@ -2612,16 +2587,16 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                owner_->showState();
                break;
        }
-       
+
        case LFUN_BREAKPARAGRAPH_SKIP:
        {
                // When at the beginning of a paragraph, remove
                // indentation and add a "defskip" at the top.
                // Otherwise, do the same as LFUN_BREAKPARAGRAPH.
                LyXText * lt = bv_->getLyXText();
-               
+
                LyXCursor cursor = lt->cursor;
-               
+
                beforeChange(lt);
                if (cursor.pos() == 0) {
                        if (cursor.par()->params().spaceTop() == VSpace(VSpace::NONE)) {
@@ -2636,7 +2611,7 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                                         cursor.par()->params().align(),
                                         cursor.par()->params().labelWidthString(), 1);
                                //update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
-                       } 
+                       }
                }
                else {
                        lt->breakParagraph(bv_, 0);
@@ -2656,14 +2631,14 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
        case LFUN_PARAGRAPH_SPACING:
        {
                LyXText * lt = bv_->getLyXText();
-               
+
                Paragraph * par = lt->cursor.par();
                Spacing::Space cur_spacing = par->params().spacing().getSpace();
                float cur_value = 1.0;
                if (cur_spacing == Spacing::Other) {
                        cur_value = par->params().spacing().getValue();
                }
-               
+
                istringstream istr(argument.c_str());
 
                string tmp;
@@ -2702,7 +2677,7 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                }
        }
        break;
-       
+
        case LFUN_INSET_TOGGLE:
        {
                LyXText * lt = bv_->getLyXText();
@@ -2712,7 +2687,7 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                lt->toggleInset(bv_);
                update(lt, BufferView::SELECT|BufferView::FITCUR);
                setState();
-       }       
+       }
                break;
 
        case LFUN_QUOTE:
@@ -2730,7 +2705,7 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                owner_->getDialogs()->createUrl(p.getAsString());
        }
        break;
-       
+
        case LFUN_INSERT_URL:
        {
                InsetCommandParams p;
@@ -2743,19 +2718,15 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                        updateInset(inset, true);
        }
        break;
-       
-       case LFUN_INSET_TEXT:
-               insertAndEditInset(new InsetText(buffer_->params));
-               break;
-       
+
        case LFUN_INSET_ERT:
                insertAndEditInset(new InsetERT(buffer_->params));
                break;
-       
+
        case LFUN_INSET_EXTERNAL:
                insertAndEditInset(new InsetExternal);
                break;
-       
+
        case LFUN_INSET_FOOTNOTE:
                insertAndEditInset(new InsetFoot(buffer_->params));
                break;
@@ -2784,23 +2755,17 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                break;
 
        case LFUN_INSET_WIDE_FLOAT:
-       {
                // check if the float type exist
                if (floatList.typeExist(argument)) {
                        InsetFloat * new_inset =
                                new InsetFloat(buffer_->params, argument);
                        new_inset->wide(true);
-                       if (insertInset(new_inset))
-                               new_inset->edit(bv_);
-                       else
-                               delete new_inset;
+                       insertAndEditInset(new_inset);
                } else {
                        lyxerr << "Non-existent float type: "
                               << argument << endl;
                }
-               
-       }
-       break;
+               break;
 
 #if 0
        case LFUN_INSET_LIST:
@@ -2811,7 +2776,7 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                insertAndEditInset(new InsetTheorem);
                break;
 #endif
-               
+
        case LFUN_INSET_CAPTION:
        {
                // Do we have a locking inset...
@@ -2831,7 +2796,7 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                }
        }
        break;
-       
+
        case LFUN_INSET_TABULAR:
        {
                int r = 2;
@@ -2859,13 +2824,13 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                        owner_->getLyXFunc()->setMessage("EOF");
        }
        break;
-       
+
        case LFUN_GETXY:
                owner_->getLyXFunc()->setMessage(tostr(bv_->getLyXText()->cursor.x())
                                                 + ' '
                                                 + tostr(bv_->getLyXText()->cursor.y()));
                break;
-               
+
        case LFUN_SETXY:
        {
                int x = 0;
@@ -2877,26 +2842,26 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                bv_->getLyXText()->setCursorFromCoordinates(bv_, x, y);
        }
        break;
-       
+
        case LFUN_GETLAYOUT:
                owner_->getLyXFunc()->setMessage(tostr(bv_->getLyXText()->cursor.par()->layout()));
                break;
-                       
+
        case LFUN_GETFONT:
        {
                LyXFont & font = bv_->getLyXText()->current_font;
-                if (font.shape() == LyXFont::ITALIC_SHAPE)
+               if (font.shape() == LyXFont::ITALIC_SHAPE)
                        owner_->getLyXFunc()->setMessage("E");
-                else if (font.shape() == LyXFont::SMALLCAPS_SHAPE)
+               else if (font.shape() == LyXFont::SMALLCAPS_SHAPE)
                        owner_->getLyXFunc()->setMessage("N");
-                else
+               else
                        owner_->getLyXFunc()->setMessage("0");
 
        }
        break;
 
        // --- accented characters ---------------------------
-               
+
        case LFUN_UMLAUT:
        case LFUN_CIRCUMFLEX:
        case LFUN_GRAVE:
@@ -2919,7 +2884,7 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                        owner_->getLyXFunc()->handleKeyFunc(action);
                } else {
                        owner_->getLyXFunc()->handleKeyFunc(action);
-                       owner_->getIntl()->getTrans()
+                       owner_->getIntl()->getTransManager()
                                .TranslateAndInsert(argument[0], bv_->getLyXText());
                        update(bv_->getLyXText(),
                               BufferView::SELECT
@@ -2927,12 +2892,16 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                               | BufferView::CHANGE);
                }
                break;
-       
+
+       case LFUN_MATH:
+               mathDispatch(bv_, argument);
+               break;
+
        case LFUN_MATH_MACRO:
                mathDispatchMathMacro(bv_, argument);
                break;
 
-       case LFUN_MATH_DELIM:     
+       case LFUN_MATH_DELIM:
                mathDispatchMathDelim(bv_, argument);
                break;
 
@@ -2952,14 +2921,14 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                mathDispatchMathDisplay(bv_, argument);
                break;
 
-       case LFUN_MATH_MODE:             // Open or create an inlined math inset 
+       case LFUN_MATH_MODE:             // Open or create an inlined math inset
                mathDispatchMathMode(bv_, argument);
                break;
-               
+
        case LFUN_GREEK:                 // Insert a single greek letter
                mathDispatchGreek(bv_, argument);
                break;
-               
+
        case LFUN_CITATION_INSERT:
        {
                InsetCommandParams p;
@@ -2972,18 +2941,18 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                        updateInset(inset, true);
        }
        break;
-                   
+
        case LFUN_INSERT_BIBTEX:
-       {   
+       {
                // ale970405+lasgoutt970425
-               // The argument can be up to two tokens separated 
+               // The argument can be up to two tokens separated
                // by a space. The first one is the bibstyle.
                string const db       = token(argument, ' ', 0);
                string const bibstyle = token(argument, ' ', 1);
 
                InsetCommandParams p("BibTeX", db, bibstyle);
                InsetBibtex * inset = new InsetBibtex(p);
-               
+
                if (insertInset(inset)) {
                        if (argument.empty())
                                inset->edit(bv_);
@@ -2991,78 +2960,56 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                        delete inset;
        }
        break;
-               
+
        // BibTeX data bases
        case LFUN_BIBDB_ADD:
        {
-               InsetBibtex * inset = 
+               InsetBibtex * inset =
                        static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
                if (inset) {
                        inset->addDatabase(argument);
                }
        }
        break;
-                   
+
        case LFUN_BIBDB_DEL:
        {
-               InsetBibtex * inset = 
+               InsetBibtex * inset =
                        static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
                if (inset) {
                        inset->delDatabase(argument);
                }
        }
        break;
-       
+
        case LFUN_BIBTEX_STYLE:
        {
-               InsetBibtex * inset = 
+               InsetBibtex * inset =
                        static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
                if (inset) {
                        inset->setOptions(argument);
                }
        }
        break;
-               
-       case LFUN_INDEX_CREATE:
-       {
-               InsetCommandParams p("index");
-               if (argument.empty()) {
-                       string const idxstring(bv_->getLyXText()->getStringToIndex(bv_));
-                       p.setContents(idxstring);
-               } else {
-                       p.setContents(argument);
-               }
 
-               owner_->getDialogs()->createIndex(p.getAsString());
-       }
-       break;
-                   
        case LFUN_INDEX_INSERT:
        {
-               InsetCommandParams p;
-               p.setFromString(argument);
-               InsetIndex * inset = new InsetIndex(p);
+               string entry = argument;
+               if (entry.empty()) {
+                       entry = bv_->getLyXText()->getStringToIndex(bv_);
+               }
 
-               if (!insertInset(inset))
+               if (entry.empty()) {
+                       owner_->getDialogs()->createIndex();
+                       break;
+               }
+
+               InsetIndex * inset = new InsetIndex(InsetCommandParams("index", entry));
+
+               if (!insertInset(inset)) {
                        delete inset;
-               else
+               } else {
                        updateInset(inset, true);
-       }
-       break;
-                   
-       case LFUN_INDEX_INSERT_LAST:
-       {
-               string const idxstring(bv_->getLyXText()->getStringToIndex(bv_));
-               if (!idxstring.empty()) {
-                       owner_->message(_("Word `")
-                                       + idxstring + _(("' indexed.")));
-                       InsetCommandParams p("index", idxstring);
-                       InsetIndex * inset = new InsetIndex(p);
-                       
-                       if (!insertInset(inset))
-                               delete inset;
-                       else
-                               updateInset(inset, true);
                }
        }
        break;
@@ -3071,20 +3018,19 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
        {
                InsetCommandParams p("printindex");
                Inset * inset = new InsetPrintIndex(p);
-               if (!insertInset(inset, "Standard"))
+               if (!insertInset(inset, tclass.defaultLayoutName()))
                        delete inset;
        }
        break;
 
        case LFUN_PARENTINSERT:
        {
-               lyxerr << "arg " << argument << endl;
                InsetCommandParams p("lyxparent", argument);
                Inset * inset = new InsetParent(p, *buffer_);
-               if (!insertInset(inset, "Standard"))
+               if (!insertInset(inset, tclass.defaultLayoutName()))
                        delete inset;
        }
-                
+
        break;
 
        case LFUN_CHILD_INSERT:
@@ -3101,17 +3047,19 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                        bv_->owner()->getDialogs()->showInclude(inset);
                }
        }
-       break; 
+       break;
 
        case LFUN_FLOAT_LIST:
-       {
-               // We should check the argument for validity. (Lgb)
-               Inset * inset = new InsetFloatList(argument);
-               if (!insertInset(inset, "Standard"))
-                       delete inset;
-       }
-       break;
-       
+               if (floatList.typeExist(argument)) {
+                       Inset * inset = new InsetFloatList(argument);
+                       if (!insertInset(inset, tclass.defaultLayoutName()))
+                               delete inset;
+               } else {
+                       lyxerr << "Non-existent float type: "
+                              << argument << endl;
+               }
+               break;
+
        case LFUN_THESAURUS_ENTRY:
        {
                string arg = argument;
@@ -3119,7 +3067,7 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                if (arg.empty()) {
                        arg = bv_->getLyXText()->selectionAsString(buffer_,
                                                                   false);
+
                        // FIXME
                        if (arg.size() > 100 || arg.empty()) {
                                // Get word or selection
@@ -3132,11 +3080,11 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                bv_->owner()->getDialogs()->showThesaurus(arg);
        }
                break;
+
        case LFUN_SELFINSERT:
        {
                if (argument.empty()) break;
-               
+
                /* Automatically delete the currently selected
                 * text and replace it with what is being
                 * typed in now. Depends on lyxrc settings
@@ -3144,7 +3092,7 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                 * true (on). */
 
                LyXText * lt = bv_->getLyXText();
-               
+
                if (lyxrc.auto_region_delete) {
                        if (lt->selection.set()) {
                                lt->cutSelection(bv_, false, false);
@@ -3153,25 +3101,27 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                                            | BufferView::FITCUR
                                            | BufferView::CHANGE);
                        }
+                       workarea().haveSelection(false);
                }
-               
+
                beforeChange(lt);
                LyXFont const old_font(lt->real_current_font);
-               
+
                string::const_iterator cit = argument.begin();
                string::const_iterator end = argument.end();
                for (; cit != end; ++cit) {
-                       owner_->getIntl()->getTrans().TranslateAndInsert(*cit, lt);
+                       owner_->getIntl()->getTransManager().
+                               TranslateAndInsert(*cit, lt);
                }
-               
+
                bv_->update(lt,
                            BufferView::SELECT
                            | BufferView::FITCUR
                            | BufferView::CHANGE);
-               
+
                lt->selection.cursor = lt->cursor;
                moveCursorUpdate(false);
-               
+
                // real_current_font.number can change so we need to
                // update the minibuffer
                if (old_font != lt->real_current_font)
@@ -3188,14 +3138,14 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
                string arg;
                if (!argument.empty())
                        arg = argument;
-               else 
+               else
                        arg = lyxrc.date_insert_format;
                char datetmp[32];
                int const datetmp_len =
                        ::strftime(datetmp, 32, arg.c_str(), now_tm);
 
                LyXText * lt = bv_->getLyXText();
-               
+
                for (int i = 0; i < datetmp_len; i++) {
                        lt->insertChar(bv_, datetmp[i]);
                        update(lt,
@@ -3212,7 +3162,7 @@ bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
        case LFUN_UNKNOWN_ACTION:
                owner_->getLyXFunc()->setErrorMessage(N_("Unknown function!"));
                break;
-       
+
        default:
                return false;
        } // end of switch
@@ -3255,38 +3205,19 @@ void BufferView::Pimpl::hfill()
 }
 
 
-void BufferView::Pimpl::protectedBlank(LyXText * lt)
-{
-       if (available()) {
-               hideCursor();
-               update(lt, BufferView::SELECT|BufferView::FITCUR);
-               InsetSpecialChar * new_inset =
-                       new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
-#ifdef WITH_WARNINGS
-#warning Why is this code different from specialChar() below? (JMarc)
-// the code in specialChar is a generic version of what used to exist
-// for other special chars. I did not merge this case because of the
-// call to updateInset(), but what does it do?
-#endif
-               if (!insertInset(new_inset))
-                       delete new_inset;
-               else
-                       updateInset(new_inset, true);
-       }
-}
-
-
 void BufferView::Pimpl::specialChar(InsetSpecialChar::Kind kind)
 {
        if (available()) {
                LyXText * lt = bv_->getLyXText();
-               
+
                hideCursor();
                update(lt, BufferView::SELECT|BufferView::FITCUR);
-               InsetSpecialChar * new_inset = 
+               InsetSpecialChar * new_inset =
                        new InsetSpecialChar(kind);
                if (!insertInset(new_inset))
                        delete new_inset;
+               else
+                       updateInset(new_inset, true);
        }
 }
 
@@ -3304,14 +3235,13 @@ void BufferView::Pimpl::smartQuote()
                c = ' ';
        else
                c = par->getChar(pos - 1);
-               
+
 
        hideCursor();
 
-       LyXLayout const & style =
-               textclasslist[bv_->buffer()->params.textclass][par->layout()];
-       
-       if (style.pass_thru ||
+       LyXLayout_ptr const & style = par->layout();
+
+       if (style->pass_thru ||
                (!insertInset(new InsetQuotes(c, bv_->buffer()->params))))
                bv_->owner()->getLyXFunc()->dispatch(LFUN_SELFINSERT, "\"");
 }
@@ -3319,18 +3249,35 @@ void BufferView::Pimpl::smartQuote()
 
 void BufferView::Pimpl::insertAndEditInset(Inset * inset)
 {
+#if 0
        if (insertInset(inset))
                inset->edit(bv_);
        else
                delete inset;
+#else
+       bool gotsel = false;
+
+       if (bv_->getLyXText()->selection.set()) {
+               bv_->getLyXText()->cutSelection(bv_, true, false);
+               gotsel = true;
+       }
+
+       if (insertInset(inset)) {
+               inset->edit(bv_);
+               if (gotsel)
+                       owner_->getLyXFunc()->dispatch(LFUN_PASTESELECTION);
+       }
+       else 
+               delete inset;
+#endif
 }
 
+
 // Open and lock an updatable inset
 bool BufferView::Pimpl::open_new_inset(UpdatableInset * new_inset, bool behind)
 {
        LyXText * lt = bv_->getLyXText();
-       
+
        beforeChange(lt);
        finishUndo();
        if (!insertInset(new_inset)) {
@@ -3355,7 +3302,7 @@ bool BufferView::Pimpl::insertInset(Inset * inset, string const & lout)
        // not quite sure if we want this...
        setCursorParUndo(bv_);
        freezeUndo();
-       
+
        beforeChange(bv_->text);
        if (!lout.empty()) {
                update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
@@ -3364,7 +3311,7 @@ bool BufferView::Pimpl::insertInset(Inset * inset, string const & lout)
 
                if (bv_->text->cursor.par()->size()) {
                        bv_->text->cursorLeft(bv_);
-                       
+
                        bv_->text->breakParagraph(bv_);
                        update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
                }
@@ -3384,17 +3331,17 @@ bool BufferView::Pimpl::insertInset(Inset * inset, string const & lout)
                }
 
                bv_->text->setLayout(bv_, lay);
-               
+
                bv_->text->setParagraph(bv_, 0, 0,
                                   0, 0,
                                   VSpace(VSpace::NONE), VSpace(VSpace::NONE),
                                   Spacing(),
-                                  LYX_ALIGN_LAYOUT, 
+                                  LYX_ALIGN_LAYOUT,
                                   string(),
                                   0);
                update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
        }
-       
+
        bv_->text->insertInset(bv_, inset);
        update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
 
@@ -3430,7 +3377,7 @@ void BufferView::Pimpl::updateInset(Inset * inset, bool mark_dirty)
                        }
                }
        }
-  
+
        // then check if the inset is a top_level inset (has no owner)
        // if yes do the update as always otherwise we have to update the
        // toplevel inset where this inset is inside
@@ -3466,13 +3413,13 @@ void BufferView::Pimpl::gotoInset(vector<Inset::Code> const & codes,
                                  bool same_content)
 {
        if (!available()) return;
-       
+
        hideCursor();
        beforeChange(bv_->text);
        update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
-       
+
        LyXCursor const & cursor = bv_->text->cursor;
+
        string contents;
        if (same_content &&
            cursor.par()->isInset(cursor.pos())) {
@@ -3482,10 +3429,10 @@ void BufferView::Pimpl::gotoInset(vector<Inset::Code> const & codes,
                        contents =
                                static_cast<InsetCommand const *>(inset)->getContents();
        }
-       
+
+
        if (!bv_->text->gotoNextInset(bv_, codes, contents)) {
-               if (bv_->text->cursor.pos() 
+               if (bv_->text->cursor.pos()
                    || bv_->text->cursor.par() != bv_->text->ownerParagraph()) {
                        LyXCursor tmp = bv_->text->cursor;
                        bv_->text->cursor.par(bv_->text->ownerParagraph());