]> git.lyx.org Git - lyx.git/blob - src/BufferView_pimpl.C
various fixes
[lyx.git] / src / BufferView_pimpl.C
1 #include <config.h>
2
3 #include <ctime>
4 #include <unistd.h>
5 #include <sys/wait.h>
6 #include <locale.h>
7
8 #ifdef __GNUG__
9 #pragma implementation
10 #endif
11
12 #include "BufferView_pimpl.h"
13 #include "WorkArea.h"
14 #include "lyxscreen.h"
15 #include "lyxtext.h"
16 #include "lyxrow.h"
17 #include "LyXView.h"
18 #include "commandtags.h"
19 #include "lyxfunc.h"
20 #include "debug.h"
21 #include "font.h"
22 #include "bufferview_funcs.h"
23 #include "TextCache.h"
24 #include "bufferlist.h"
25 #include "lyx_gui_misc.h"
26 #include "lyxrc.h"
27 #include "intl.h"
28 #include "support/LAssert.h"
29 #include "support/lstrings.h"
30 #include "frontends/Dialogs.h"
31 #include "insets/insetbib.h"
32 #include "insets/insettext.h"
33 /// added for Dispatch functions
34 #include "lyx_cb.h"
35 #include "frontends/FileDialog.h"
36 #include "lyx_main.h"
37 #include "FloatList.h"
38 #include "support/filetools.h"
39 #include "support/lyxfunctional.h"
40 #include "insets/inseturl.h"
41 #include "insets/insetlatexaccent.h"
42 #include "insets/insettoc.h"
43 #include "insets/insetref.h"
44 #include "insets/insetparent.h"
45 #include "insets/insetindex.h"
46 #include "insets/insetnote.h"
47 #include "insets/insetinclude.h"
48 #include "insets/insetcite.h"
49 #include "insets/insetert.h"
50 #include "insets/insetexternal.h"
51 #include "insets/insetgraphics.h"
52 #include "insets/insetfoot.h"
53 #include "insets/insetmarginal.h"
54 #include "insets/insetminipage.h"
55 #include "insets/insetfloat.h"
56 #include "insets/insettabular.h"
57 #if 0
58 #include "insets/insettheorem.h"
59 #include "insets/insetlist.h"
60 #endif
61 #include "insets/insetcaption.h"
62 #include "insets/insetfloatlist.h"
63 #include "insets/insetspecialchar.h"
64 #include "gettext.h"
65 #include "ParagraphParameters.h"
66 #include "undo_funcs.h"
67 #include "mathed/formulabase.h"
68
69 extern LyXTextClass::size_type current_layout;
70 extern int greek_kb_flag;
71
72 using std::vector;
73 using std::find_if;
74 using std::find;
75 using std::pair;
76 using std::endl;
77 using std::make_pair;
78 using std::min;
79 using SigC::slot;
80
81 /* the selection possible is needed, that only motion events are 
82  * used, where the bottom press event was on the drawing area too */
83 bool selection_possible = false;
84
85 extern BufferList bufferlist;
86 extern char ascii_type;
87
88 extern bool math_insert_greek(BufferView *, char);
89 extern void sigchldchecker(pid_t pid, int * status);
90 extern int bibitemMaxWidth(BufferView *, LyXFont const &);
91
92
93 namespace {
94
95 const unsigned int saved_positions_num = 20;
96
97 inline
98 void waitForX()
99 {
100         XSync(fl_get_display(), 0);
101 }
102
103
104 void SetXtermCursor(Window win)
105 {
106         static Cursor cursor;
107         static bool cursor_undefined = true;
108         if (cursor_undefined){
109                 cursor = XCreateFontCursor(fl_get_display(), XC_xterm);
110                 XFlush(fl_get_display());
111                 cursor_undefined = false;
112         }
113         XDefineCursor(fl_get_display(), win, cursor);
114         XFlush(fl_get_display());
115 }
116
117 } // anon namespace
118
119
120 BufferView::Pimpl::Pimpl(BufferView * b, LyXView * o,
121              int xpos, int ypos, int width, int height)
122         : bv_(b), owner_(o), buffer_(0),
123           current_scrollbar_value(0), cursor_timeout(400),
124           workarea_(xpos, ypos, width, height), using_xterm_cursor(false),
125           inset_slept(false)
126 {
127         // Setup the signals
128         workarea_.scrollCB.connect(slot(this, &BufferView::Pimpl::scrollCB));
129         workarea_.workAreaExpose
130                 .connect(slot(this, &BufferView::Pimpl::workAreaExpose));
131         workarea_.workAreaEnter
132                 .connect(slot(this, &BufferView::Pimpl::enterView));
133         workarea_.workAreaLeave
134                 .connect(slot(this, &BufferView::Pimpl::leaveView));
135         workarea_.workAreaButtonPress
136                 .connect(slot(this, &BufferView::Pimpl::workAreaButtonPress));
137         workarea_.workAreaButtonRelease
138                 .connect(slot(this,
139                               &BufferView::Pimpl::workAreaButtonRelease));
140         workarea_.workAreaMotionNotify
141                 .connect(slot(this, &BufferView::Pimpl::workAreaMotionNotify));
142         workarea_.workAreaDoubleClick
143                 .connect(slot(this, &BufferView::Pimpl::doubleClick));
144         workarea_.workAreaTripleClick
145                 .connect(slot(this, &BufferView::Pimpl::tripleClick));
146         workarea_.workAreaKeyPress
147                 .connect(slot(this, &BufferView::Pimpl::workAreaKeyPress));
148         
149         cursor_timeout.timeout.connect(slot(this,
150                                             &BufferView::Pimpl::cursorToggle));
151         cursor_timeout.start();
152         workarea_.setFocus();
153         saved_positions.resize(saved_positions_num);
154 }
155
156
157 Painter & BufferView::Pimpl::painter() 
158 {
159         return workarea_.getPainter();
160 }
161
162
163 void BufferView::Pimpl::buffer(Buffer * b)
164 {
165         lyxerr[Debug::INFO] << "Setting buffer in BufferView ("
166                             << b << ")" << endl;
167         if (buffer_) {
168                 insetSleep();
169                 buffer_->delUser(bv_);
170
171                 // Put the old text into the TextCache, but
172                 // only if the buffer is still loaded.
173                 // Also set the owner of the test to 0
174                 //              bv_->text->owner(0);
175                 textcache.add(buffer_, workarea_.workWidth(), bv_->text);
176                 if (lyxerr.debugging())
177                         textcache.show(lyxerr, "BufferView::buffer");
178                 
179                 bv_->text = 0;
180         }
181
182         // Set current buffer
183         buffer_ = b;
184
185         if (bufferlist.getState() == BufferList::CLOSING) return;
186         
187         // Nuke old image
188         // screen is always deleted when the buffer is changed.
189         screen_.reset(0);
190
191         // If we are closing the buffer, use the first buffer as current
192         if (!buffer_) {
193                 buffer_ = bufferlist.first();
194         }
195
196         if (buffer_) {
197                 lyxerr[Debug::INFO] << "Buffer addr: " << buffer_ << endl;
198                 buffer_->addUser(bv_);
199                 // If we don't have a text object for this, we make one
200                 if (bv_->text == 0) {
201                         resizeCurrentBuffer();
202                 } else {
203                         updateScreen();
204                         updateScrollbar();
205                 }
206                 bv_->text->first = screen_->topCursorVisible(bv_->text);
207                 owner_->updateMenubar();
208                 owner_->updateToolbar();
209                 // Similarly, buffer-dependent dialogs should be updated or
210                 // hidden. This should go here because some dialogs (eg ToC)
211                 // require bv_->text.
212                 owner_->getDialogs()->updateBufferDependent(true);
213                 redraw();
214                 insetWakeup();
215         } else {
216                 lyxerr[Debug::INFO] << "  No Buffer!" << endl;
217                 owner_->updateMenubar();
218                 owner_->updateToolbar();
219                 owner_->getDialogs()->hideBufferDependent();
220                 updateScrollbar();
221                 workarea_.redraw();
222
223                 // Also remove all remaining text's from the testcache.
224                 // (there should not be any!) (if there is any it is a
225                 // bug!)
226                 if (lyxerr.debugging())
227                         textcache.show(lyxerr, "buffer delete all");
228                 textcache.clear();
229         }
230         // should update layoutchoice even if we don't have a buffer.
231         owner_->updateLayoutChoice();
232
233         owner_->updateWindowTitle();
234 }
235
236
237 void BufferView::Pimpl::resize(int xpos, int ypos, int width, int height)
238 {
239         workarea_.resize(xpos, ypos, width, height);
240         update(bv_->text, SELECT);
241         redraw();
242 }
243
244
245 void BufferView::Pimpl::resize()
246 {
247         if (buffer_)
248                 resizeCurrentBuffer();
249 }
250
251
252 void BufferView::Pimpl::redraw()
253 {
254         lyxerr[Debug::INFO] << "BufferView::redraw()" << endl;
255         workarea_.redraw();
256 }
257
258
259 bool BufferView::Pimpl::fitCursor(LyXText * text)
260 {
261         lyx::Assert(screen_.get());
262
263         bool ret;
264
265         if (bv_->theLockingInset()) {
266                 bv_->theLockingInset()->fitInsetCursor(bv_);
267                 ret = true;
268         } else {
269                 ret = screen_->fitCursor(text, bv_);
270         }
271
272         bv_->owner()->getDialogs()->updateParagraph();
273         if (ret)
274             updateScrollbar();
275         return ret;
276 }
277
278
279 void BufferView::Pimpl::redoCurrentBuffer()
280 {
281         lyxerr[Debug::INFO] << "BufferView::redoCurrentBuffer" << endl;
282         if (buffer_ && bv_->text) {
283                 resize();
284                 owner_->updateLayoutChoice();
285         }
286 }
287
288
289 int BufferView::Pimpl::resizeCurrentBuffer()
290 {
291         lyxerr[Debug::INFO] << "resizeCurrentBuffer" << endl;
292         
293         Paragraph * par = 0;
294         Paragraph * selstartpar = 0;
295         Paragraph * selendpar = 0;
296         UpdatableInset * the_locking_inset = 0;
297         
298         Paragraph::size_type pos = 0;
299         Paragraph::size_type selstartpos = 0;
300         Paragraph::size_type selendpos = 0;
301         bool selection = false;
302         bool mark_set  = false;
303
304         owner_->prohibitInput();
305
306         owner_->message(_("Formatting document..."));
307
308         if (bv_->text) {
309                 par = bv_->text->cursor.par();
310                 pos = bv_->text->cursor.pos();
311                 selstartpar = bv_->text->selection.start.par();
312                 selstartpos = bv_->text->selection.start.pos();
313                 selendpar = bv_->text->selection.end.par();
314                 selendpos = bv_->text->selection.end.pos();
315                 selection = bv_->text->selection.set();
316                 mark_set = bv_->text->selection.mark();
317                 the_locking_inset = bv_->theLockingInset();
318                 delete bv_->text;
319                 bv_->text = new LyXText(bv_);
320                 bv_->text->init(bv_);
321         } else {
322                 // See if we have a text in TextCache that fits
323                 // the new buffer_ with the correct width.
324                 bv_->text = textcache.findFit(buffer_, workarea_.workWidth());
325                 if (bv_->text) {
326                         if (lyxerr.debugging()) {
327                                 lyxerr << "Found a LyXText that fits:\n";
328                                 textcache.show(lyxerr, make_pair(buffer_, make_pair(workarea_.workWidth(), bv_->text)));
329                         }
330                         // Set the owner of the newly found text
331                         //      bv_->text->owner(bv_);
332                         if (lyxerr.debugging())
333                                 textcache.show(lyxerr, "resizeCurrentBuffer");
334                 } else {
335                         bv_->text = new LyXText(bv_);
336                         bv_->text->init(bv_);
337                 }
338         }
339         updateScreen();
340
341         if (par) {
342                 bv_->text->selection.set(true);
343                 /* at this point just to avoid the Delete-Empty-Paragraph
344                  * Mechanism when setting the cursor */
345                 bv_->text->selection.mark(mark_set);
346                 if (selection) {
347                         bv_->text->setCursor(bv_, selstartpar, selstartpos);
348                         bv_->text->selection.cursor = bv_->text->cursor;
349                         bv_->text->setCursor(bv_, selendpar, selendpos);
350                         bv_->text->setSelection(bv_);
351                         bv_->text->setCursor(bv_, par, pos);
352                 } else {
353                         bv_->text->setCursor(bv_, par, pos);
354                         bv_->text->selection.cursor = bv_->text->cursor;
355                         bv_->text->selection.set(false);
356                 }
357                 // remake the inset locking
358                 bv_->theLockingInset(the_locking_inset);
359         }
360         bv_->text->first = screen_->topCursorVisible(bv_->text);
361         buffer_->resizeInsets(bv_);
362         // this will scroll the screen such that the cursor becomes visible
363         updateScrollbar();
364         redraw();
365
366         setState();
367         owner_->allowInput();
368
369         /// clear the "Formatting Document" message 
370         owner_->message("");
371  
372         /// get rid of the splash screen if it's not gone already
373         owner_->getDialogs()->destroySplash();
374  
375         return 0;
376 }
377
378
379 void BufferView::Pimpl::updateScreen()
380 {
381         // Regenerate the screen.
382         screen_.reset(new LyXScreen(workarea_));
383 }
384
385
386 void BufferView::Pimpl::updateScrollbar()
387 {
388         /* If the text is smaller than the working area, the scrollbar
389          * maximum must be the working area height. No scrolling will 
390          * be possible */
391         if (!bv_->text) {
392                 workarea_.setScrollbar(0, 1.0);
393                 return;
394         }
395
396         long const text_height = bv_->text->height;
397
398         double const lineh = bv_->text->defaultHeight();
399         double const slider_size =
400                 (text_height == 0) ? 1.0 : 1.0 / double(text_height);
401
402         static long old_text_height = 0;
403         static double old_lineh = 0;
404         static double old_slider_size = 0;
405
406         if (text_height != old_text_height) {
407                 workarea_.setScrollbarBounds(0, text_height - workarea_.height());
408                 old_text_height = text_height;
409         }
410         if (lineh != old_lineh) {
411                 workarea_.setScrollbarIncrements(lineh);
412                 old_lineh = lineh;
413         }
414         if (current_scrollbar_value != bv_->text->first
415             || slider_size != old_slider_size) {
416                 current_scrollbar_value = bv_->text->first;
417                 workarea_.setScrollbar(current_scrollbar_value, slider_size);
418                 old_slider_size = slider_size;
419         }
420 }
421
422
423 // Callback for scrollbar slider
424 void BufferView::Pimpl::scrollCB(double value)
425 {
426         if (!buffer_) return;
427
428         current_scrollbar_value = long(value);
429         if (current_scrollbar_value < 0)
430                 current_scrollbar_value = 0;
431    
432         if (!screen_.get())
433                 return;
434
435         screen_->draw(bv_->text, bv_, current_scrollbar_value);
436
437         if (!lyxrc.cursor_follows_scrollbar) {
438                 waitForX();
439                 return;
440         }
441  
442         LyXText * vbt = bv_->text;
443  
444         int const height = vbt->defaultHeight();
445         int const first = static_cast<int>((bv_->text->first + height));
446         int const last = static_cast<int>((bv_->text->first + workarea_.height() - height));
447
448         if (vbt->cursor.y() < first)
449                 vbt->setCursorFromCoordinates(bv_, 0, first);
450         else if (vbt->cursor.y() > last)
451                 vbt->setCursorFromCoordinates(bv_, 0, last);
452
453         waitForX();
454 }
455
456
457 int BufferView::Pimpl::scrollUp(long time)
458 {
459         if (!buffer_) return 0;
460         if (!screen_.get()) return 0;
461    
462         double value = workarea_.getScrollbarValue();
463    
464         if (value == 0) return 0;
465
466         float add_value =  (bv_->text->defaultHeight()
467                             + float(time) * float(time) * 0.125);
468    
469         if (add_value > workarea_.height())
470                 add_value = float(workarea_.height() -
471                                   bv_->text->defaultHeight());
472    
473         value -= add_value;
474
475         if (value < 0)
476                 value = 0;
477    
478         workarea_.setScrollbarValue(value);
479    
480         scrollCB(value); 
481         return 0;
482 }
483
484
485 int BufferView::Pimpl::scrollDown(long time)
486 {
487         if (!buffer_) return 0;
488         if (!screen_.get()) return 0;
489    
490         double value = workarea_.getScrollbarValue();
491         pair<float, float> p = workarea_.getScrollbarBounds();
492         double const max = p.second;
493         
494         if (value == max) return 0;
495
496         float add_value =  (bv_->text->defaultHeight()
497                             + float(time) * float(time) * 0.125);
498    
499         if (add_value > workarea_.height())
500                 add_value = float(workarea_.height() -
501                                   bv_->text->defaultHeight());
502    
503         value += add_value;
504    
505         if (value > max)
506                 value = max;
507
508         workarea_.setScrollbarValue(value);
509         
510         scrollCB(value); 
511         return 0;
512 }
513
514
515 void BufferView::Pimpl::workAreaKeyPress(KeySym keysym, unsigned int state)
516 {
517         bv_->owner()->getLyXFunc()->processKeySym(keysym, state);
518 }
519
520
521 void BufferView::Pimpl::workAreaMotionNotify(int x, int y, unsigned int state)
522 {
523         // Only use motion with button 1
524         if (!(state & Button1MotionMask))
525                 return;
526
527         if (!buffer_ || !screen_.get()) return;
528
529         // Check for inset locking
530         if (bv_->theLockingInset()) {
531                 LyXCursor cursor = bv_->text->cursor;
532                 LyXFont font = bv_->text->getFont(buffer_,
533                                                   cursor.par(), cursor.pos());
534                 int width = bv_->theLockingInset()->width(bv_, font);
535                 int inset_x = font.isVisibleRightToLeft()
536                         ? cursor.x() - width : cursor.x();
537                 int start_x = inset_x + bv_->theLockingInset()->scroll();
538                 bv_->theLockingInset()->
539                         insetMotionNotify(bv_,
540                                           x - start_x,
541                                           y - cursor.y() + bv_->text->first,
542                                           state);
543                 return;
544         }
545    
546         /* The test for not selection possible is needed, that only motion
547            events are used, where the bottom press event was on
548            the drawing area too */
549         if (!selection_possible)
550                 return;
551  
552         screen_->hideCursor();
553
554         bv_->text->setCursorFromCoordinates(bv_, x, y + bv_->text->first);
555       
556         if (!bv_->text->selection.set())
557                 update(bv_->text, BufferView::UPDATE); // Maybe an empty line was deleted
558       
559         bv_->text->setSelection(bv_);
560         screen_->toggleToggle(bv_->text, bv_);
561         fitCursor(bv_->text);
562         screen_->showCursor(bv_->text, bv_);
563 }
564
565
566 // Single-click on work area
567 void BufferView::Pimpl::workAreaButtonPress(int xpos, int ypos,
568                                             unsigned int button)
569 {
570         if (!buffer_ || !screen_.get()) return;
571
572         Inset * inset_hit = checkInsetHit(bv_->text, xpos, ypos, button);
573
574         // ok ok, this is a hack.
575         if (button == 4 || button == 5) {
576                 switch (button) {
577                 case 4:
578                         scrollUp(lyxrc.wheel_jump); // default 100, set in lyxrc
579                         break;
580                 case 5:
581                         scrollDown(lyxrc.wheel_jump);
582                         break;
583                 }
584         }
585         
586         if (bv_->theLockingInset()) {
587                 // We are in inset locking mode
588                 
589                 /* Check whether the inset was hit. If not reset mode,
590                    otherwise give the event to the inset */
591                 if (inset_hit == bv_->theLockingInset()) {
592                         bv_->theLockingInset()->
593                                 insetButtonPress(bv_,
594                                                  xpos, ypos,
595                                                  button);
596                         return;
597                 } else {
598                         bv_->unlockInset(bv_->theLockingInset());
599                 }
600         }
601         
602         if (!inset_hit)
603                 selection_possible = true;
604         screen_->hideCursor();
605
606         int const screen_first = bv_->text->first;
607         
608         // Middle button press pastes if we have a selection
609         bool paste_internally = false;
610         if (button == 2
611             && bv_->text->selection.set()) {
612                 owner_->getLyXFunc()->dispatch(LFUN_COPY);
613                 paste_internally = true;
614         }
615         
616         // Clear the selection
617         screen_->toggleSelection(bv_->text, bv_);
618         bv_->text->clearSelection(bv_);
619         bv_->text->fullRebreak(bv_);
620         screen_->update(bv_->text, bv_);
621         updateScrollbar();
622         
623         // Single left click in math inset?
624         if ((inset_hit != 0) &&
625             (inset_hit->editable()==Inset::HIGHLY_EDITABLE)) {
626                 // Highly editable inset, like math
627                 UpdatableInset * inset = static_cast<UpdatableInset *>(inset_hit);
628                 selection_possible = false;
629                 owner_->updateLayoutChoice();
630                 owner_->message(inset->editMessage());
631                 inset->insetButtonPress(bv_, xpos, ypos, button);
632                 inset->edit(bv_, xpos, ypos, button);
633                 return;
634         } 
635         
636         // Right click on a footnote flag opens float menu
637         if (button == 3) { 
638                 selection_possible = false;
639                 return;
640         }
641         
642         if (!inset_hit) // otherwise it was already set in checkInsetHit(...)
643                 bv_->text->setCursorFromCoordinates(bv_, xpos, ypos + screen_first);
644         finishUndo();
645         bv_->text->selection.cursor = bv_->text->cursor;
646         bv_->text->cursor.x_fix(bv_->text->cursor.x());
647         
648         owner_->updateLayoutChoice();
649         if (fitCursor(bv_->text)) {
650                 selection_possible = false;
651         }
652         
653         // Insert primary selection with middle mouse
654         // if there is a local selection in the current buffer,
655         // insert this
656         if (button == 2) {
657                 if (paste_internally)
658                         owner_->getLyXFunc()->dispatch(LFUN_PASTE);
659                 else
660                         owner_->getLyXFunc()->dispatch(LFUN_PASTESELECTION,
661                                                        "paragraph");
662                 selection_possible = false;
663                 return;
664         }
665 }
666
667
668 void BufferView::Pimpl::doubleClick(int /*x*/, int /*y*/, unsigned int button) 
669 {
670         // select a word
671         if (!buffer_)
672             return;
673
674         LyXText * text = bv_->getLyXText();
675
676         if (text->bv_owner && bv_->theLockingInset())
677             return;
678
679         if (screen_.get() && button == 1) {
680             if (text->bv_owner) {
681                 screen_->hideCursor();
682                 screen_->toggleSelection(text, bv_);
683                 text->selectWord(bv_, LyXText::WHOLE_WORD_STRICT);
684                 screen_->toggleSelection(text, bv_, false);
685             } else {
686                 text->selectWord(bv_, LyXText::WHOLE_WORD_STRICT);
687             }
688             /* This will fit the cursor on the screen
689              * if necessary */
690             update(text, BufferView::SELECT|BufferView::FITCUR);
691         }
692 }
693
694
695 void BufferView::Pimpl::tripleClick(int /*x*/, int /*y*/, unsigned int button)
696 {
697         // select a line
698         if (buffer_)
699                 return;
700
701         LyXText * text = bv_->getLyXText();
702
703         if (text->bv_owner && bv_->theLockingInset())
704             return;
705
706         if (screen_.get() && (button == 1)) {
707                 screen_->hideCursor();
708                 screen_->toggleSelection(text, bv_);
709                 text->cursorHome(bv_);
710                 text->selection.cursor = text->cursor;
711                 text->cursorEnd(bv_);
712                 text->setSelection(bv_);
713                 screen_->toggleSelection(text, bv_, false);
714                 /* This will fit the cursor on the screen
715                  * if necessary */
716                 update(text, BufferView::SELECT|BufferView::FITCUR);
717         }
718 }
719
720
721 void BufferView::Pimpl::enterView()
722 {
723         if (active() && available()) {
724                 SetXtermCursor(workarea_.getWin());
725                 using_xterm_cursor = true;
726         }
727 }
728
729
730 void BufferView::Pimpl::leaveView()
731 {
732         if (using_xterm_cursor) {
733                 XUndefineCursor(fl_get_display(), workarea_.getWin());
734                 using_xterm_cursor = false;
735         }
736 }
737
738
739 void BufferView::Pimpl::workAreaButtonRelease(int x, int y,
740                                               unsigned int button)
741 {
742         if (!buffer_ || !screen_.get()) return;
743
744         // If we hit an inset, we have the inset coordinates in these
745         // and inset_hit points to the inset.  If we do not hit an
746         // inset, inset_hit is 0, and inset_x == x, inset_y == y.
747         Inset * inset_hit = checkInsetHit(bv_->text, x, y, button);
748
749         if (bv_->theLockingInset()) {
750                 // We are in inset locking mode.
751
752                 /* LyX does a kind of work-area grabbing for insets.
753                    Only a ButtonPress Event outside the inset will 
754                    force a insetUnlock. */
755                 bv_->theLockingInset()->
756                         insetButtonRelease(bv_, x, y, button);
757                 return;
758         }
759         
760         selection_possible = false;
761         
762         if (button == 2)
763                 return;
764
765         setState();
766         owner_->showState();
767
768         // Did we hit an editable inset?
769         if (inset_hit) {
770                 // Inset like error, notes and figures
771                 selection_possible = false;
772
773                 // CHECK fix this proper in 0.13
774
775                 // Following a ref shouldn't issue
776                 // a push on the undo-stack
777                 // anylonger, now that we have
778                 // keybindings for following
779                 // references and returning from
780                 // references.  IMHO though, it
781                 // should be the inset's own business
782                 // to push or not push on the undo
783                 // stack. They don't *have* to
784                 // alter the document...
785                 // (Joacim)
786                 // ...or maybe the SetCursorParUndo()
787                 // below isn't necessary at all anylonger?
788                 if (inset_hit->lyxCode() == Inset::REF_CODE) {
789                         setCursorParUndo(bv_);
790                 }
791
792                 owner_->message(inset_hit->editMessage());
793
794                 if (inset_hit->editable()==Inset::HIGHLY_EDITABLE) {
795                         // Highly editable inset, like math
796                         UpdatableInset *inset = (UpdatableInset *)inset_hit;
797                         inset->insetButtonRelease(bv_, x, y, button);
798                 } else {
799                         inset_hit->insetButtonRelease(bv_, x, y, button);
800                         inset_hit->edit(bv_, x, y, button);
801                 }
802                 return;
803         }
804
805         // check whether we want to open a float
806         if (bv_->text) {
807                 bool hit = false;
808                 char c = ' ';
809                 if (bv_->text->cursor.pos() <
810                     bv_->text->cursor.par()->size()) {
811                         c = bv_->text->cursor.par()->
812                                 getChar(bv_->text->cursor.pos());
813                 }
814                         if (bv_->text->cursor.pos() - 1 >= 0) {
815                         c = bv_->text->cursor.par()->
816                                 getChar(bv_->text->cursor.pos() - 1);
817                 }
818                 if (hit == true) {
819                         selection_possible = false;
820                         return;
821                 }
822         }
823
824         // Maybe we want to edit a bibitem ale970302
825         if (bv_->text->cursor.par()->bibkey && x < 20 + 
826             bibitemMaxWidth(bv_, textclasslist.
827                             TextClass(buffer_->
828                                       params.textclass).defaultfont())) {
829                 bv_->text->cursor.par()->bibkey->edit(bv_, 0, 0, 0);
830         }
831
832         return;
833 }
834
835
836 /* 
837  * Returns an inset if inset was hit. 0 otherwise.
838  * If hit, the coordinates are changed relative to the inset. 
839  * Otherwise coordinates are not changed, and false is returned.
840  */
841 Inset * BufferView::Pimpl::checkInsetHit(LyXText * text, int & x, int & y,
842                                          unsigned int /* button */)
843 {
844         if (!screen_.get())
845                 return 0;
846   
847         int y_tmp = y + text->first;
848   
849         LyXCursor cursor;
850         text->setCursorFromCoordinates(bv_, cursor, x, y_tmp);
851         text->setCursor(bv_, cursor, cursor.par(),cursor.pos(),true);
852
853
854         if (cursor.pos() < cursor.par()->size()
855             && cursor.par()->getChar(cursor.pos()) == Paragraph::META_INSET
856             && cursor.par()->getInset(cursor.pos())
857             && cursor.par()->getInset(cursor.pos())->editable()) {
858
859                 // Check whether the inset really was hit
860                 Inset * tmpinset = cursor.par()->getInset(cursor.pos());
861                 LyXFont font = text->getFont(buffer_,
862                                                   cursor.par(), cursor.pos());
863                 int const width = tmpinset->width(bv_, font);
864                 int const inset_x = font.isVisibleRightToLeft()
865                         ? cursor.x() - width : cursor.x();
866                 int const start_x = inset_x + tmpinset->scroll();
867                 int const end_x = inset_x + width;
868
869                 if (x > start_x && x < end_x
870                     && y_tmp > cursor.y() - tmpinset->ascent(bv_, font)
871                     && y_tmp < cursor.y() + tmpinset->descent(bv_, font)) {
872                         text->setCursor(bv_, cursor.par(),cursor.pos(), true);
873                         x = x - start_x;
874                         // The origin of an inset is on the baseline
875                         y = y_tmp - (text->cursor.y()); 
876                         return tmpinset;
877                 }
878         }
879
880         if ((cursor.pos() - 1 >= 0) &&
881             (cursor.par()->getChar(cursor.pos()-1) == Paragraph::META_INSET) &&
882             (cursor.par()->getInset(cursor.pos() - 1)) &&
883             (cursor.par()->getInset(cursor.pos() - 1)->editable())) {
884                 Inset * tmpinset = cursor.par()->getInset(cursor.pos()-1);
885                 LyXFont font = text->getFont(buffer_, cursor.par(),
886                                                   cursor.pos()-1);
887                 int const width = tmpinset->width(bv_, font);
888                 int const inset_x = font.isVisibleRightToLeft()
889                         ? cursor.x() : cursor.x() - width;
890                 int const start_x = inset_x + tmpinset->scroll();
891                 int const end_x = inset_x + width;
892
893                 if (x > start_x && x < end_x
894                     && y_tmp > cursor.y() - tmpinset->ascent(bv_, font)
895                     && y_tmp < cursor.y() + tmpinset->descent(bv_, font)) {
896 #if 0
897                         if (move_cursor && (tmpinset != bv_->theLockingInset()))
898 #endif
899                                 text->setCursor(bv_, cursor.par(),
900                                                 cursor.pos() - 1, true);
901                         x = x - start_x;
902                         // The origin of an inset is on the baseline
903                         y = y_tmp - (text->cursor.y()); 
904                         return tmpinset;
905                 }
906         }
907         return 0;
908 }
909
910
911 void BufferView::Pimpl::workAreaExpose()
912 {
913         static int work_area_width;
914         static unsigned int work_area_height;
915
916         bool const widthChange = workarea_.workWidth() != work_area_width;
917         bool const heightChange = workarea_.height() != work_area_height;
918
919         // update from work area
920         work_area_width = workarea_.workWidth();
921         work_area_height = workarea_.height();
922         if (buffer_ != 0) {
923                 if (widthChange) {
924                         // The visible LyXView need a resize
925                         owner_->resize();
926
927                         // Remove all texts from the textcache
928                         // This is not _really_ what we want to do. What
929                         // we really want to do is to delete in textcache
930                         // that does not have a BufferView with matching
931                         // width, but as long as we have only one BufferView
932                         // deleting all gives the same result.
933                         if (lyxerr.debugging())
934                                 textcache.show(lyxerr, "Expose delete all");
935                         textcache.clear();
936                 } else if (heightChange) {
937                         // Rebuild image of current screen
938                         updateScreen();
939                         // fitCursor() ensures we don't jump back
940                         // to the start of the document on vertical
941                         // resize
942                         fitCursor(bv_->text);
943
944                         // The main window size has changed, repaint most stuff
945                         redraw();
946                 } else if (screen_.get())
947                     screen_->redraw(bv_->text, bv_);
948         } else {
949                 // Grey box when we don't have a buffer
950                 workarea_.greyOut();
951         }
952
953         // always make sure that the scrollbar is sane.
954         updateScrollbar();
955         owner_->updateLayoutChoice();
956         return;
957 }
958
959
960 void BufferView::Pimpl::update()
961 {
962         if (screen_.get() &&
963                 (!bv_->theLockingInset() || !bv_->theLockingInset()->nodraw()))
964         {
965                 screen_->update(bv_->text, bv_);
966         }
967 }
968
969 // Values used when calling update:
970 // -3 - update
971 // -2 - update, move sel_cursor if selection, fitcursor
972 // -1 - update, move sel_cursor if selection, fitcursor, mark dirty
973 //  0 - update, move sel_cursor if selection, fitcursor 
974 //  1 - update, move sel_cursor if selection, fitcursor, mark dirty
975 //  3 - update, move sel_cursor if selection
976 //
977 // update -
978 // a simple redraw of the parts that need refresh
979 //
980 // move sel_cursor if selection -
981 // the text's sel_cursor is moved if there is selection is progress
982 //
983 // fitcursor -
984 // fitCursor() is called and the scrollbar updated
985 //
986 // mark dirty -
987 // the buffer is marked dirty.
988 //
989 // enum {
990 //       UPDATE = 0,
991 //       SELECT = 1,
992 //       FITCUR = 2,
993 //       CHANGE = 4 
994 // };
995 //
996 // UPDATE_ONLY = UPDATE;
997 // UPDATE_SELECT = UPDATE | SELECT;
998 // UPDATE_SELECT_MOVE = UPDATE | SELECT | FITCUR;
999 // UPDATE_SELECT_MOVE_AFTER_CHANGE = UPDATE | SELECT | FITCUR | CHANGE;
1000 //
1001 // update(-3) -> update(0)         -> update(0) -> update(UPDATE)
1002 // update(-2) -> update(1 + 2)     -> update(3) -> update(SELECT|FITCUR)
1003 // update(-1) -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
1004 // update(1)  -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
1005 // update(3)  -> update(1)         -> update(1) -> update(SELECT)
1006
1007 void BufferView::Pimpl::update(LyXText * text, BufferView::UpdateCodes f)
1008 {
1009         owner_->updateLayoutChoice();
1010
1011         if (!text->selection.set() && (f & SELECT)) {
1012                 text->selection.cursor = text->cursor;
1013         }
1014
1015         text->fullRebreak(bv_);
1016
1017         if (text->inset_owner) {
1018                 text->inset_owner->setUpdateStatus(bv_, InsetText::NONE);
1019             updateInset(text->inset_owner, true);
1020         } else {
1021             update();
1022         }
1023                 
1024         if ((f & FITCUR)) {
1025                 fitCursor(text);
1026         }
1027
1028         if ((f & CHANGE)) {
1029                 buffer_->markDirty();
1030         }
1031 }
1032
1033
1034 // Callback for cursor timer
1035 void BufferView::Pimpl::cursorToggle()
1036 {
1037         // Quite a nice place for asyncron Inset updating, isn't it?
1038         // Actually no! This is run even if no buffer exist... so (Lgb)
1039         if (!buffer_) {
1040                 cursor_timeout.restart();
1041                 return;
1042         }
1043  
1044         int status = 1;
1045         int const pid = waitpid(static_cast<pid_t>(0), &status, WNOHANG);
1046         if (pid == -1) // error find out what is wrong
1047                 ; // ignore it for now.
1048         else if (pid > 0)
1049                 sigchldchecker(pid, &status);
1050
1051         updatelist.update(bv_);
1052         
1053         if (!screen_.get()) {
1054                 cursor_timeout.restart();
1055                 return;
1056         }
1057
1058         if (!bv_->theLockingInset()) {
1059                 screen_->cursorToggle(bv_->text, bv_);
1060         } else {
1061                 bv_->theLockingInset()->toggleInsetCursor(bv_);
1062         }
1063         
1064         cursor_timeout.restart();
1065 }
1066
1067
1068 void BufferView::Pimpl::cursorPrevious(LyXText * text)
1069 {
1070         if (!text->cursor.row()->previous())
1071                 return;
1072         
1073         int y = text->first;
1074         if (text->inset_owner)
1075                 y += bv_->text->first;
1076         Row * cursorrow = text->cursor.row();
1077         text->setCursorFromCoordinates(bv_, bv_->text->cursor.x_fix(), y);
1078         finishUndo();
1079         // This is to allow jumping over large insets
1080         if ((cursorrow == text->cursor.row()))
1081                 text->cursorUp(bv_);
1082         
1083         if (text->inset_owner ||
1084             text->cursor.row()->height() < workarea_.height())
1085                 screen_->draw(bv_->text, bv_,
1086                               text->cursor.y()
1087                               - text->cursor.row()->baseline()
1088                               + text->cursor.row()->height()
1089                               - workarea_.height() + 1 );
1090         updateScrollbar();
1091 }
1092
1093
1094 void BufferView::Pimpl::cursorNext(LyXText * text)
1095 {
1096         if (!text->cursor.row()->next())
1097                 return;
1098         
1099         int y = text->first + workarea_.height();
1100 //      if (text->inset_owner)
1101 //              y += bv_->text->first;
1102         text->getRowNearY(y);
1103     
1104         Row * cursorrow = text->cursor.row();
1105         text->setCursorFromCoordinates(bv_, text->cursor.x_fix(), y); // + workarea_->height());
1106         finishUndo();
1107         // This is to allow jumping over large insets
1108         if ((cursorrow == bv_->text->cursor.row()))
1109                 text->cursorDown(bv_);
1110         
1111         if (text->inset_owner ||
1112             text->cursor.row()->height() < workarea_.height())
1113                 screen_->draw(bv_->text, bv_, text->cursor.y() -
1114                               text->cursor.row()->baseline());
1115         updateScrollbar();
1116 }
1117
1118
1119 bool BufferView::Pimpl::available() const
1120 {
1121         if (buffer_ && bv_->text) return true;
1122         return false;
1123 }
1124
1125
1126 void BufferView::Pimpl::beforeChange(LyXText * text)
1127 {
1128         toggleSelection();
1129         text->clearSelection(bv_);
1130 }
1131
1132
1133 void BufferView::Pimpl::savePosition(unsigned int i)
1134 {
1135         if (i >= saved_positions_num)
1136                 return;
1137         saved_positions[i] = Position(buffer_->fileName(),
1138                                       bv_->text->cursor.par()->id(),
1139                                       bv_->text->cursor.pos());
1140         if (i > 0) {
1141                 ostringstream str;
1142                 str << _("Saved bookmark") << ' ' << i;
1143                 owner_->message(str.str().c_str());
1144         }
1145 }
1146
1147
1148 void BufferView::Pimpl::restorePosition(unsigned int i)
1149 {
1150         if (i >= saved_positions_num)
1151                 return;
1152
1153         string const fname = saved_positions[i].filename;
1154
1155         beforeChange(bv_->text);
1156
1157         if (fname != buffer_->fileName()) {
1158                 Buffer * b = bufferlist.exists(fname) ?
1159                         bufferlist.getBuffer(fname) :
1160                         bufferlist.loadLyXFile(fname); // don't ask, just load it
1161                 if (b != 0 ) buffer(b);
1162         }
1163
1164         Paragraph * par = buffer_->getParFromID(saved_positions[i].par_id);
1165         if (!par)
1166                 return;
1167
1168         bv_->text->setCursor(bv_, par,
1169                              min(par->size(), saved_positions[i].par_pos));
1170
1171         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
1172         if (i > 0) {
1173                 ostringstream str;
1174                 str << _("Moved to bookmark") << ' ' << i;
1175                 owner_->message(str.str().c_str());
1176         }
1177 }
1178
1179
1180 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
1181 {
1182         if (i >= saved_positions_num)
1183                 return false;
1184
1185         return !saved_positions[i].filename.empty();
1186 }
1187
1188
1189 void BufferView::Pimpl::setState()
1190 {
1191         if (!lyxrc.rtl_support)
1192                 return;
1193
1194         LyXText * text = bv_->getLyXText();
1195         if (text->real_current_font.isRightToLeft()
1196 #ifndef NO_LATEX
1197             &&
1198             text->real_current_font.latex() != LyXFont::ON
1199 #endif
1200                 ) {
1201                 if (owner_->getIntl()->keymap == Intl::PRIMARY)
1202                         owner_->getIntl()->KeyMapSec();
1203         } else {
1204                 if (owner_->getIntl()->keymap == Intl::SECONDARY)
1205                         owner_->getIntl()->KeyMapPrim();
1206         }
1207 }
1208
1209
1210 void BufferView::Pimpl::insetSleep()
1211 {
1212         if (bv_->theLockingInset() && !inset_slept) {
1213                 bv_->theLockingInset()->getCursorPos(bv_, bv_->slx, bv_->sly);
1214                 bv_->theLockingInset()->insetUnlock(bv_);
1215                 inset_slept = true;
1216         }
1217 }
1218
1219
1220 void BufferView::Pimpl::insetWakeup()
1221 {
1222         if (bv_->theLockingInset() && inset_slept) {
1223                 bv_->theLockingInset()->edit(bv_, bv_->slx, bv_->sly, 0);
1224                 inset_slept = false;
1225         }
1226 }
1227
1228
1229 void BufferView::Pimpl::insetUnlock()
1230 {
1231         if (bv_->theLockingInset()) {
1232                 if (!inset_slept)
1233                         bv_->theLockingInset()->insetUnlock(bv_);
1234                 bv_->theLockingInset(0);
1235                 finishUndo();
1236                 inset_slept = false;
1237         }
1238 }
1239
1240
1241 bool BufferView::Pimpl::focus() const
1242 {
1243         return workarea_.hasFocus();
1244 }
1245
1246
1247 void BufferView::Pimpl::focus(bool f)
1248 {
1249         if (f) workarea_.setFocus();
1250 }
1251
1252
1253 bool BufferView::Pimpl::active() const
1254 {
1255         return workarea_.active();
1256 }
1257
1258
1259 bool BufferView::Pimpl::belowMouse() const 
1260 {
1261         return workarea_.belowMouse();
1262 }
1263
1264
1265 void BufferView::Pimpl::showCursor()
1266 {
1267         if (screen_.get()) {
1268                 if (bv_->theLockingInset())
1269                         bv_->theLockingInset()->showInsetCursor(bv_);
1270                 else
1271                         screen_->showCursor(bv_->text, bv_);
1272         }
1273 }
1274
1275
1276 void BufferView::Pimpl::hideCursor()
1277 {
1278         if (screen_.get()) {
1279                 if (!bv_->theLockingInset())
1280 //                      bv_->theLockingInset()->hideInsetCursor(bv_);
1281 //              else
1282                         screen_->hideCursor();
1283         }
1284 }
1285
1286
1287 void BufferView::Pimpl::toggleSelection(bool b)
1288 {
1289         if (screen_.get()) {
1290                 if (bv_->theLockingInset())
1291                         bv_->theLockingInset()->toggleSelection(bv_, b);
1292                 screen_->toggleSelection(bv_->text, bv_, b);
1293         }
1294 }
1295
1296
1297 void BufferView::Pimpl::toggleToggle()
1298 {
1299         if (screen_.get())
1300                 screen_->toggleToggle(bv_->text, bv_);
1301 }
1302
1303
1304 void BufferView::Pimpl::center() 
1305 {
1306         beforeChange(bv_->text);
1307         if (bv_->text->cursor.y() > static_cast<int>((workarea_.height() / 2))) {
1308                 screen_->draw(bv_->text, bv_, bv_->text->cursor.y() - workarea_.height() / 2);
1309         } else {
1310                 screen_->draw(bv_->text, bv_, 0);
1311         }
1312         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
1313         redraw();
1314 }
1315
1316
1317 void BufferView::Pimpl::pasteClipboard(bool asPara) 
1318 {
1319         if (!buffer_) return;
1320
1321         screen_->hideCursor();
1322         beforeChange(bv_->text);
1323         
1324         string const clip(workarea_.getClipboard());
1325         
1326         if (clip.empty()) return;
1327
1328         if (asPara) {
1329                 bv_->text->insertStringAsParagraphs(bv_, clip);
1330         } else {
1331                 bv_->text->insertStringAsLines(bv_, clip);
1332         }
1333         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1334 }
1335
1336
1337 void BufferView::Pimpl::stuffClipboard(string const & stuff) const
1338 {
1339         workarea_.putClipboard(stuff);
1340 }
1341
1342
1343 /*
1344  * Dispatch functions for actions which can be valid for BufferView->text
1345  * and/or InsetText->text!!!
1346  */
1347
1348
1349 inline
1350 void BufferView::Pimpl::moveCursorUpdate(bool selecting)
1351 {
1352         LyXText * lt = bv_->getLyXText();
1353         
1354         if (selecting || lt->selection.mark()) {
1355                 lt->setSelection(bv_);
1356                 if (lt->bv_owner)
1357                         toggleToggle();
1358         }
1359         update(lt, BufferView::SELECT|BufferView::FITCUR);
1360         showCursor();
1361         
1362         /* ---> Everytime the cursor is moved, show the current font state. */
1363         // should this too me moved out of this func?
1364         //owner->showState();
1365         setState();
1366 }
1367
1368
1369 Inset * BufferView::Pimpl::getInsetByCode(Inset::Code code)
1370 {
1371         LyXCursor cursor = bv_->getLyXText()->cursor;
1372         Buffer::inset_iterator it =
1373                 find_if(Buffer::inset_iterator(
1374                         cursor.par(), cursor.pos()),
1375                         buffer_->inset_iterator_end(),
1376                         lyx::compare_memfun(&Inset::lyxCode, code));
1377         return it != buffer_->inset_iterator_end() ? (*it) : 0;
1378 }
1379
1380
1381 void BufferView::Pimpl::MenuInsertLyXFile(string const & filen)
1382 {
1383         string filename = filen;
1384
1385         if (filename.empty()) {
1386                 // Launch a file browser
1387                 string initpath = lyxrc.document_path;
1388
1389                 if (available()) {
1390                         string const trypath = owner_->buffer()->filepath;
1391                         // If directory is writeable, use this as default.
1392                         if (IsDirWriteable(trypath) == 1)
1393                                 initpath = trypath;
1394                 }
1395
1396                 FileDialog fileDlg(bv_->owner(),
1397                                    _("Select LyX document to insert"),
1398                         LFUN_FILE_INSERT,
1399                         make_pair(string(_("Documents")),
1400                                   string(lyxrc.document_path)),
1401                         make_pair(string(_("Examples")),
1402                                   string(AddPath(system_lyxdir, "examples"))));
1403
1404                 FileDialog::Result result =
1405                         fileDlg.Select(initpath,
1406                                        _("*.lyx| LyX Documents (*.lyx)"));
1407  
1408                 if (result.first == FileDialog::Later)
1409                         return;
1410
1411                 filename = result.second;
1412
1413                 // check selected filename
1414                 if (filename.empty()) {
1415                         owner_->message(_("Canceled."));
1416                         return;
1417                 }
1418         }
1419
1420         // get absolute path of file and add ".lyx" to the filename if
1421         // necessary
1422         filename = FileSearch(string(), filename, "lyx");
1423
1424         string const disp_fn(MakeDisplayPath(filename));
1425         
1426         ostringstream s1;
1427         s1 << _("Inserting document") << ' '
1428            << disp_fn << " ...";
1429         owner_->message(s1.str().c_str());
1430         bool const res = bv_->insertLyXFile(filename);
1431         if (res) {
1432                 ostringstream str;
1433                 str << _("Document") << ' ' << disp_fn
1434                     << ' ' << _("inserted.");
1435                 owner_->message(str.str().c_str());
1436         } else {
1437                 ostringstream str;
1438                 str << _("Could not insert document") << ' '
1439                     << disp_fn;
1440                 owner_->message(str.str().c_str());
1441         }
1442 }
1443
1444
1445 bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
1446 {
1447         lyxerr[Debug::ACTION] << "BufferView::Pimpl::Dispatch: action["
1448                               << action <<"] arg[" << argument << "]" << endl;
1449         
1450         switch (action) {
1451                 // --- Misc -------------------------------------------
1452         case LFUN_APPENDIX:
1453         {
1454                 if (available()) {
1455                         LyXText * lt = bv_->getLyXText();
1456                         lt->toggleAppendix(bv_);
1457                         update(lt,
1458                                BufferView::SELECT
1459                                | BufferView::FITCUR
1460                                | BufferView::CHANGE);
1461                 }
1462         }
1463         break;
1464
1465         case LFUN_TOC_INSERT:
1466         {
1467                 InsetCommandParams p;
1468                 p.setCmdName("tableofcontents");
1469                 Inset * inset = new InsetTOC(p);
1470                 if (!insertInset(inset, "Standard"))
1471                         delete inset;
1472                 break;
1473         }
1474                 
1475         case LFUN_TABULAR_FEATURE:
1476         case LFUN_SCROLL_INSET:
1477                 // this is not handled here as this funktion is only aktive
1478                 // if we have a locking_inset and that one is (or contains)
1479                 // a tabular-inset
1480                 break;
1481
1482         case LFUN_INSET_GRAPHICS:
1483         {
1484                 Inset * new_inset = new InsetGraphics;
1485                 if (!insertInset(new_inset)) {
1486                         delete new_inset;
1487                 } else {
1488                         // this is need because you don't use a inset->Edit()
1489                         updateInset(new_inset, true);
1490                         new_inset->edit(bv_);
1491                 }
1492                 break;
1493         }
1494                 
1495         case LFUN_PASTE:
1496                 bv_->paste();
1497                 setState();
1498                 break;
1499                 
1500         case LFUN_PASTESELECTION:
1501         {
1502                 bool asPara = false;
1503                 if (argument == "paragraph") asPara = true;
1504                 pasteClipboard(asPara);
1505         }
1506         break;
1507         
1508         case LFUN_CUT:
1509                 bv_->cut();
1510                 break;
1511                 
1512         case LFUN_COPY:
1513                 bv_->copy();
1514                 break;
1515                 
1516         case LFUN_LAYOUT_COPY:
1517                 bv_->copyEnvironment();
1518                 break;
1519                 
1520         case LFUN_LAYOUT_PASTE:
1521                 bv_->pasteEnvironment();
1522                 setState();
1523                 break;
1524                 
1525         case LFUN_GOTOERROR:
1526                 gotoInset(Inset::ERROR_CODE, false);
1527                 break;
1528                 
1529         case LFUN_GOTONOTE:
1530                 gotoInset(Inset::IGNORE_CODE, false);
1531                 break;
1532
1533         case LFUN_REFERENCE_GOTO:
1534         {
1535                 vector<Inset::Code> tmp;
1536                 tmp.push_back(Inset::LABEL_CODE);
1537                 tmp.push_back(Inset::REF_CODE);
1538                 gotoInset(tmp, true);
1539                 break;
1540         }
1541
1542         case LFUN_HYPHENATION:
1543                 specialChar(InsetSpecialChar::HYPHENATION);
1544                 break;
1545                 
1546         case LFUN_LIGATURE_BREAK:
1547                 specialChar(InsetSpecialChar::LIGATURE_BREAK);
1548                 break;
1549                 
1550         case LFUN_LDOTS:
1551                 specialChar(InsetSpecialChar::LDOTS);
1552                 break;
1553                 
1554         case LFUN_END_OF_SENTENCE:
1555                 specialChar(InsetSpecialChar::END_OF_SENTENCE);
1556                 break;
1557
1558         case LFUN_MENU_SEPARATOR:
1559                 specialChar(InsetSpecialChar::MENU_SEPARATOR);
1560                 break;
1561                 
1562         case LFUN_HFILL:
1563                 hfill();
1564                 break;
1565                 
1566         case LFUN_DEPTH:
1567                 changeDepth(bv_, bv_->getLyXText(), 0);
1568                 break;
1569                 
1570         case LFUN_DEPTH_MIN:
1571                 changeDepth(bv_, bv_->getLyXText(), -1);
1572                 break;
1573                 
1574         case LFUN_DEPTH_PLUS:
1575                 changeDepth(bv_, bv_->getLyXText(), 1);
1576                 break;
1577                 
1578         case LFUN_FREE:
1579                 owner_->getDialogs()->setUserFreeFont();
1580                 break;
1581
1582 #ifndef NO_LATEX
1583         case LFUN_TEX:
1584                 Tex(bv_);
1585                 setState();
1586                 owner_->showState();
1587                 break;
1588 #endif
1589                 
1590         case LFUN_FILE_INSERT:
1591         {
1592                 MenuInsertLyXFile(argument);
1593         }
1594         break;
1595         
1596         case LFUN_FILE_INSERT_ASCII_PARA:
1597                 InsertAsciiFile(bv_, argument, true);
1598                 break;
1599
1600         case LFUN_FILE_INSERT_ASCII:
1601                 InsertAsciiFile(bv_, argument, false);
1602                 break;
1603                 
1604         case LFUN_LAYOUT:
1605         {
1606                 lyxerr[Debug::INFO] << "LFUN_LAYOUT: (arg) "
1607                                     << argument << endl;
1608                 
1609                 // Derive layout number from given argument (string)
1610                 // and current buffer's textclass (number). */    
1611                 LyXTextClassList::ClassList::size_type tclass =
1612                         buffer_->params.textclass;
1613                 pair <bool, LyXTextClass::size_type> layout = 
1614                         textclasslist.NumberOfLayout(tclass, argument);
1615
1616                 // If the entry is obsolete, use the new one instead.
1617                 if (layout.first) {
1618                         string obs = textclasslist.Style(tclass,layout.second)
1619                                 .obsoleted_by();
1620                         if (!obs.empty()) 
1621                                 layout = 
1622                                         textclasslist.NumberOfLayout(tclass, obs);
1623                 }
1624
1625                 // see if we found the layout number:
1626                 if (!layout.first) {
1627                         owner_->getLyXFunc()->setErrorMessage(
1628                                 string(N_("Layout ")) + argument +
1629                                 N_(" not known"));
1630                         break;
1631                 }
1632
1633                 if (current_layout != layout.second) {
1634                         LyXText * lt = bv_->getLyXText();
1635                         hideCursor();
1636                         current_layout = layout.second;
1637                         update(lt,
1638                                BufferView::SELECT
1639                                | BufferView::FITCUR);
1640                         lt->setLayout(bv_, layout.second);
1641                         owner_->setLayout(layout.second);
1642                         update(lt,
1643                                BufferView::SELECT
1644                                | BufferView::FITCUR
1645                                | BufferView::CHANGE);
1646                         setState();
1647                 }
1648         }
1649         break;
1650
1651         case LFUN_LANGUAGE:
1652                 Lang(bv_, argument);
1653                 setState();
1654                 owner_->showState();
1655                 break;
1656
1657         case LFUN_EMPH:
1658                 Emph(bv_);
1659                 owner_->showState();
1660                 break;
1661
1662         case LFUN_BOLD:
1663                 Bold(bv_);
1664                 owner_->showState();
1665                 break;
1666                 
1667         case LFUN_NOUN:
1668                 Noun(bv_);
1669                 owner_->showState();
1670                 break;
1671                 
1672         case LFUN_CODE:
1673                 Code(bv_);
1674                 owner_->showState();
1675                 break;
1676                 
1677         case LFUN_SANS:
1678                 Sans(bv_);
1679                 owner_->showState();
1680                 break;
1681                 
1682         case LFUN_ROMAN:
1683                 Roman(bv_);
1684                 owner_->showState();
1685                 break;
1686                 
1687         case LFUN_DEFAULT:
1688                 StyleReset(bv_);
1689                 owner_->showState();
1690                 break;
1691                 
1692         case LFUN_UNDERLINE:
1693                 Underline(bv_);
1694                 owner_->showState();
1695                 break;
1696                 
1697         case LFUN_FONT_SIZE:
1698                 FontSize(bv_, argument);
1699                 owner_->showState();
1700                 break;
1701                 
1702         case LFUN_FONT_STATE:
1703                 owner_->getLyXFunc()->setMessage(CurrentState(bv_));
1704                 break;
1705                 
1706         case LFUN_UPCASE_WORD:
1707         {
1708                 LyXText * lt = bv_->getLyXText();
1709                 
1710                 update(lt,
1711                        BufferView::SELECT
1712                        | BufferView::FITCUR);
1713                 lt->changeCase(bv_, LyXText::text_uppercase);
1714                 if (lt->inset_owner)
1715                         updateInset(lt->inset_owner, true);
1716                 update(lt,
1717                        BufferView::SELECT
1718                        | BufferView::FITCUR
1719                        | BufferView::CHANGE);
1720         }
1721         break;
1722                 
1723         case LFUN_LOWCASE_WORD:
1724         {
1725                 LyXText * lt = bv_->getLyXText();
1726                 
1727                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1728                 lt->changeCase(bv_, LyXText::text_lowercase);
1729                 if (lt->inset_owner)
1730                         updateInset(lt->inset_owner, true);
1731                 update(lt,
1732                        BufferView::SELECT
1733                        | BufferView::FITCUR
1734                        | BufferView::CHANGE);
1735         }
1736         break;
1737                 
1738         case LFUN_CAPITALIZE_WORD:
1739         {
1740                 LyXText * lt = bv_->getLyXText();
1741                 
1742                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1743                 lt->changeCase(bv_, LyXText::text_capitalization);
1744                 if (lt->inset_owner)
1745                         updateInset(lt->inset_owner, true);
1746                 update(lt,
1747                        BufferView::SELECT
1748                        | BufferView::FITCUR
1749                        | BufferView::CHANGE);
1750         }
1751         break;
1752
1753         case LFUN_TRANSPOSE_CHARS:
1754         {
1755                 LyXText * lt = bv_->getLyXText();
1756                 
1757                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1758                 lt->transposeChars(*bv_);
1759                 if (lt->inset_owner)
1760                         updateInset(lt->inset_owner, true);
1761                 update(lt,
1762                        BufferView::SELECT
1763                        | BufferView::FITCUR
1764                        | BufferView::CHANGE);
1765         }
1766         break;
1767                 
1768                                           
1769         case LFUN_INSERT_LABEL:
1770                 MenuInsertLabel(bv_, argument);
1771                 break;
1772                 
1773         case LFUN_REF_INSERT:
1774                 if (argument.empty()) {
1775                         InsetCommandParams p("ref");
1776                         owner_->getDialogs()->createRef(p.getAsString());
1777                 } else {
1778                         InsetCommandParams p;
1779                         p.setFromString(argument);
1780
1781                         InsetRef * inset = new InsetRef(p, *buffer_);
1782                         if (!insertInset(inset))
1783                                 delete inset;
1784                         else
1785                                 updateInset(inset, true);
1786                 }
1787                 break;
1788
1789         case LFUN_BOOKMARK_SAVE:
1790                 savePosition(strToUnsignedInt(argument));
1791                 break;
1792
1793         case LFUN_BOOKMARK_GOTO:
1794                 restorePosition(strToUnsignedInt(argument));
1795                 break;
1796
1797         case LFUN_REF_GOTO:
1798         {
1799                 string label(argument);
1800                 if (label.empty()) {
1801                         InsetRef * inset = 
1802                                 static_cast<InsetRef*>(getInsetByCode(Inset::REF_CODE));
1803                         if (inset) {
1804                                 label = inset->getContents();
1805                                 savePosition(0);
1806                         }
1807                 }
1808                 
1809                 if (!label.empty()) {
1810                         //bv_->savePosition(0);
1811                         if (!bv_->gotoLabel(label))
1812                                 WriteAlert(_("Error"), 
1813                                            _("Couldn't find this label"), 
1814                                            _("in current document."));
1815                 }
1816         }
1817         break;
1818                 
1819                 // --- Cursor Movements -----------------------------
1820         case LFUN_RIGHT:
1821         {
1822                 LyXText * lt = bv_->getLyXText();
1823                 
1824                 bool is_rtl = lt->cursor.par()->isRightToLeftPar(buffer_->params);
1825                 if (!lt->selection.mark())
1826                         beforeChange(lt);
1827                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1828                 if (is_rtl)
1829                         lt->cursorLeft(bv_, false);
1830                 if (lt->cursor.pos() < lt->cursor.par()->size()
1831                     && lt->cursor.par()->getChar(lt->cursor.pos())
1832                     == Paragraph::META_INSET
1833                     && lt->cursor.par()->getInset(lt->cursor.pos())
1834                     && lt->cursor.par()->getInset(lt->cursor.pos())->editable() == Inset::HIGHLY_EDITABLE){
1835                         Inset * tmpinset = lt->cursor.par()->getInset(lt->cursor.pos());
1836                         owner_->getLyXFunc()->setMessage(tmpinset->editMessage());
1837                         if (is_rtl)
1838                                 tmpinset->edit(bv_, false);
1839                         else
1840                                 tmpinset->edit(bv_);
1841                         break;
1842                 }
1843                 if (!is_rtl)
1844                         lt->cursorRight(bv_, false);
1845                 finishUndo();
1846                 moveCursorUpdate(false);
1847                 owner_->showState();
1848         }
1849         break;
1850                 
1851         case LFUN_LEFT:
1852         {
1853                 // This is soooo ugly. Isn`t it possible to make
1854                 // it simpler? (Lgb)
1855                 LyXText * lt = bv_->getLyXText();
1856                 bool is_rtl = lt->cursor.par()->isRightToLeftPar(buffer_->params);
1857                 if (!lt->selection.mark())
1858                         beforeChange(lt);
1859                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1860                 LyXCursor const cur = lt->cursor;
1861                 if (!is_rtl)
1862                         lt->cursorLeft(bv_, false);
1863                 if ((is_rtl || cur != lt->cursor) && // only if really moved!
1864                     lt->cursor.pos() < lt->cursor.par()->size() &&
1865                     (lt->cursor.par()->getChar(lt->cursor.pos()) ==
1866                      Paragraph::META_INSET) &&
1867                     lt->cursor.par()->getInset(lt->cursor.pos()) &&
1868                     (lt->cursor.par()->getInset(lt->cursor.pos())->editable()
1869                      == Inset::HIGHLY_EDITABLE))
1870                 {
1871                         Inset * tmpinset = lt->cursor.par()->getInset(lt->cursor.pos());
1872                         owner_->getLyXFunc()->setMessage(tmpinset->editMessage());
1873                         if (is_rtl)
1874                                 tmpinset->edit(bv_);
1875                         else
1876                                 tmpinset->edit(bv_, false);
1877                         break;
1878                 }
1879                 if  (is_rtl)
1880                         lt->cursorRight(bv_, false);
1881
1882                 finishUndo();
1883                 moveCursorUpdate(false);
1884                 owner_->showState();
1885         }
1886         break;
1887                 
1888         case LFUN_UP:
1889         {
1890                 LyXText * lt = bv_->getLyXText();
1891                 
1892                 if (!lt->selection.mark())
1893                         beforeChange(lt);
1894                 update(lt, BufferView::UPDATE);
1895                 lt->cursorUp(bv_);
1896                 finishUndo();
1897                 moveCursorUpdate(false);
1898                 owner_->showState();
1899         }
1900         break;
1901                 
1902         case LFUN_DOWN:
1903         {
1904                 LyXText * lt = bv_->getLyXText();
1905                 
1906                 if (!lt->selection.mark())
1907                         beforeChange(lt);
1908                 update(lt, BufferView::UPDATE);
1909                 lt->cursorDown(bv_);
1910                 finishUndo();
1911                 moveCursorUpdate(false);
1912                 owner_->showState();
1913         }
1914         break;
1915
1916         case LFUN_UP_PARAGRAPH:
1917         {
1918                 LyXText * lt = bv_->getLyXText();
1919                 
1920                 if (!lt->selection.mark())
1921                         beforeChange(lt);
1922                 update(lt, BufferView::UPDATE);
1923                 lt->cursorUpParagraph(bv_);
1924                 finishUndo();
1925                 moveCursorUpdate(false);
1926                 owner_->showState();
1927         }
1928         break;
1929                 
1930         case LFUN_DOWN_PARAGRAPH:
1931         {
1932                 LyXText * lt = bv_->getLyXText();
1933                 
1934                 if (!lt->selection.mark())
1935                         beforeChange(lt);
1936                 update(lt, BufferView::UPDATE);
1937                 lt->cursorDownParagraph(bv_);
1938                 finishUndo();
1939                 moveCursorUpdate(false);
1940                 owner_->showState();
1941         }
1942         break;
1943                 
1944         case LFUN_PRIOR:
1945         {
1946                 LyXText * lt = bv_->getLyXText();
1947                 
1948                 if (!lt->selection.mark())
1949                         beforeChange(lt);
1950                 update(lt, BufferView::UPDATE);
1951                 cursorPrevious(lt);
1952                 finishUndo();
1953                 moveCursorUpdate(false);
1954                 owner_->showState();
1955         }
1956         break;
1957                 
1958         case LFUN_NEXT:
1959         {
1960                 LyXText * lt = bv_->getLyXText();
1961                 
1962                 if (!lt->selection.mark())
1963                         beforeChange(lt);
1964                 update(lt, BufferView::UPDATE);
1965                 cursorNext(lt);
1966                 finishUndo();
1967                 moveCursorUpdate(false);
1968                 owner_->showState();
1969         }
1970         break;
1971                 
1972         case LFUN_HOME:
1973         {
1974                 LyXText * lt = bv_->getLyXText();
1975                 
1976                 if (!lt->selection.mark())
1977                         beforeChange(lt);
1978                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1979                 lt->cursorHome(bv_);
1980                 finishUndo();
1981                 moveCursorUpdate(false);
1982                 owner_->showState();
1983         }
1984         break;
1985                 
1986         case LFUN_END:
1987         {
1988                 LyXText * lt = bv_->getLyXText();
1989                 
1990                 if (!lt->selection.mark())
1991                         beforeChange(lt);
1992                 update(lt,
1993                        BufferView::SELECT|BufferView::FITCUR);
1994                 lt->cursorEnd(bv_);
1995                 finishUndo();
1996                 moveCursorUpdate(false);
1997                 owner_->showState();
1998         }
1999         break;
2000                 
2001         case LFUN_SHIFT_TAB:
2002         case LFUN_TAB:
2003         {
2004                 LyXText * lt = bv_->getLyXText();
2005                 
2006                 if (!lt->selection.mark())
2007                         beforeChange(lt);
2008                 update(lt,
2009                        BufferView::SELECT|BufferView::FITCUR);
2010                 lt->cursorTab(bv_);
2011                 finishUndo();
2012                 moveCursorUpdate(false);
2013                 owner_->showState();
2014         }
2015         break;
2016                 
2017         case LFUN_WORDRIGHT:
2018         {
2019                 LyXText * lt = bv_->getLyXText();
2020                 
2021                 if (!lt->selection.mark())
2022                         beforeChange(lt);
2023                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2024                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2025                         lt->cursorLeftOneWord(bv_);
2026                 else
2027                         lt->cursorRightOneWord(bv_);
2028                 finishUndo();
2029                 moveCursorUpdate(false);
2030                 owner_->showState();
2031         }
2032         break;
2033                 
2034         case LFUN_WORDLEFT:
2035         {
2036                 LyXText * lt = bv_->getLyXText();
2037                 
2038                 if (!lt->selection.mark())
2039                         beforeChange(lt);
2040                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2041                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2042                         lt->cursorRightOneWord(bv_);
2043                 else
2044                         lt->cursorLeftOneWord(bv_);
2045                 finishUndo();
2046                 moveCursorUpdate(false);
2047                 owner_->showState();
2048         }
2049         break;
2050                 
2051         case LFUN_BEGINNINGBUF:
2052         {
2053                 LyXText * lt = bv_->getLyXText();
2054                 
2055                 if (!lt->selection.mark())
2056                         beforeChange(lt);
2057                 update(lt,
2058                        BufferView::SELECT|BufferView::FITCUR);
2059                 lt->cursorTop(bv_);
2060                 finishUndo();
2061                 moveCursorUpdate(false);
2062                 owner_->showState();
2063         }
2064         break;
2065                 
2066         case LFUN_ENDBUF:
2067         {
2068                 LyXText * lt = bv_->getLyXText();
2069                 
2070                 if (!lt->selection.mark())
2071                         beforeChange(lt);
2072                 update(lt,
2073                        BufferView::SELECT|BufferView::FITCUR);
2074                 lt->cursorBottom(bv_);
2075                 finishUndo();
2076                 moveCursorUpdate(false);
2077                 owner_->showState();
2078         }
2079         break;
2080       
2081                 /* cursor selection ---------------------------- */
2082         case LFUN_RIGHTSEL:
2083         {
2084                 LyXText * lt = bv_->getLyXText();
2085                 
2086                 update(lt,
2087                        BufferView::SELECT|BufferView::FITCUR);
2088                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2089                         lt->cursorLeft(bv_);
2090                 else
2091                         lt->cursorRight(bv_);
2092                 finishUndo();
2093                 moveCursorUpdate(true);
2094                 owner_->showState();
2095         }
2096         break;
2097                 
2098         case LFUN_LEFTSEL:
2099         {
2100                 LyXText * lt = bv_->getLyXText();
2101                 
2102                 update(lt,
2103                        BufferView::SELECT|BufferView::FITCUR);
2104                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2105                         lt->cursorRight(bv_);
2106                 else
2107                         lt->cursorLeft(bv_);
2108                 finishUndo();
2109                 moveCursorUpdate(true);
2110                 owner_->showState();
2111         }
2112         break;
2113                 
2114         case LFUN_UPSEL:
2115         {
2116                 LyXText * lt = bv_->getLyXText();
2117                 
2118                 update(lt,
2119                        BufferView::SELECT|BufferView::FITCUR);
2120                 lt->cursorUp(bv_);
2121                 finishUndo();
2122                 moveCursorUpdate(true);
2123                 owner_->showState();
2124         }
2125         break;
2126                 
2127         case LFUN_DOWNSEL:
2128         {
2129                 LyXText * lt = bv_->getLyXText();
2130                 
2131                 update(lt,
2132                        BufferView::SELECT|BufferView::FITCUR);
2133                 lt->cursorDown(bv_);
2134                 finishUndo();
2135                 moveCursorUpdate(true);
2136                 owner_->showState();
2137         }
2138         break;
2139
2140         case LFUN_UP_PARAGRAPHSEL:
2141         {
2142                 LyXText * lt = bv_->getLyXText();
2143                 
2144                 update(lt,
2145                        BufferView::SELECT|BufferView::FITCUR);
2146                 lt->cursorUpParagraph(bv_);
2147                 finishUndo();
2148                 moveCursorUpdate(true);
2149                 owner_->showState();
2150         }
2151         break;
2152                 
2153         case LFUN_DOWN_PARAGRAPHSEL:
2154         {
2155                 LyXText * lt = bv_->getLyXText();
2156                 
2157                 update(lt,
2158                        BufferView::SELECT|BufferView::FITCUR);
2159                 lt->cursorDownParagraph(bv_);
2160                 finishUndo();
2161                 moveCursorUpdate(true);
2162                 owner_->showState();
2163         }
2164         break;
2165                 
2166         case LFUN_PRIORSEL:
2167         {
2168                 LyXText * lt = bv_->getLyXText();
2169                 
2170                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2171                 cursorPrevious(lt);
2172                 finishUndo();
2173                 moveCursorUpdate(true);
2174                 owner_->showState();
2175         }
2176         break;
2177                 
2178         case LFUN_NEXTSEL:
2179         {
2180                 LyXText * lt = bv_->getLyXText();
2181                 
2182                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2183                 cursorNext(lt);
2184                 finishUndo();
2185                 moveCursorUpdate(true);
2186                 owner_->showState();
2187         }
2188         break;
2189                 
2190         case LFUN_HOMESEL:
2191         {
2192                 LyXText * lt = bv_->getLyXText();
2193                 
2194                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2195                 lt->cursorHome(bv_);
2196                 finishUndo();
2197                 moveCursorUpdate(true);
2198                 owner_->showState();
2199         }
2200         break;
2201                 
2202         case LFUN_ENDSEL:
2203         {
2204                 LyXText * lt = bv_->getLyXText();
2205                 
2206                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2207                 lt->cursorEnd(bv_);
2208                 finishUndo();
2209                 moveCursorUpdate(true);
2210                 owner_->showState();
2211         }
2212         break;
2213                 
2214         case LFUN_WORDRIGHTSEL:
2215         {
2216                 LyXText * lt = bv_->getLyXText();
2217                 
2218                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2219                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2220                         lt->cursorLeftOneWord(bv_);
2221                 else
2222                         lt->cursorRightOneWord(bv_);
2223                 finishUndo();
2224                 moveCursorUpdate(true);
2225                 owner_->showState();
2226         }
2227         break;
2228                 
2229         case LFUN_WORDLEFTSEL:
2230         {
2231                 LyXText * lt = bv_->getLyXText();
2232                 
2233                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2234                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2235                         lt->cursorRightOneWord(bv_);
2236                 else
2237                         lt->cursorLeftOneWord(bv_);
2238                 finishUndo();
2239                 moveCursorUpdate(true);
2240                 owner_->showState();
2241         }
2242         break;
2243                 
2244         case LFUN_BEGINNINGBUFSEL:
2245         {
2246                 LyXText * lt = bv_->getLyXText();
2247                 
2248                 if (lt->inset_owner)
2249                         break;
2250                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2251                 lt->cursorTop(bv_);
2252                 finishUndo();
2253                 moveCursorUpdate(true);
2254                 owner_->showState();
2255         }
2256         break;
2257                 
2258         case LFUN_ENDBUFSEL:
2259         {
2260                 LyXText * lt = bv_->getLyXText();
2261                 
2262                 if (lt->inset_owner)
2263                         break;
2264                 update(lt,
2265                        BufferView::SELECT|BufferView::FITCUR);
2266                 lt->cursorBottom(bv_);
2267                 finishUndo();
2268                 moveCursorUpdate(true);
2269                 owner_->showState();
2270         }
2271         break;
2272
2273                 // --- text changing commands ------------------------
2274         case LFUN_BREAKLINE:
2275         {
2276                 LyXText * lt = bv_->getLyXText();
2277
2278                 beforeChange(lt);
2279                 lt->insertChar(bv_, Paragraph::META_NEWLINE);
2280                 update(lt,
2281                        BufferView::SELECT
2282                        | BufferView::FITCUR
2283                        | BufferView::CHANGE);
2284                 moveCursorUpdate(false);
2285         }
2286         break;
2287                 
2288         case LFUN_PROTECTEDSPACE:
2289         {
2290                 LyXText * lt = bv_->getLyXText();
2291
2292                 LyXLayout const & style = textclasslist
2293                         .Style(buffer_->params.textclass,
2294                                lt->cursor.par()->getLayout());
2295
2296                 if (style.free_spacing) {
2297                         lt->insertChar(bv_, ' ');
2298                         update(lt,
2299                                BufferView::SELECT
2300                                | BufferView::FITCUR
2301                                | BufferView::CHANGE);
2302                 } else {
2303                         protectedBlank(lt);
2304                 }
2305                 moveCursorUpdate(false);
2306         }
2307         break;
2308                 
2309         case LFUN_SETMARK:
2310         {
2311                 LyXText * lt = bv_->getLyXText();
2312
2313                 if (lt->selection.mark()) {
2314                         beforeChange(lt);
2315                         update(lt,
2316                                BufferView::SELECT
2317                                | BufferView::FITCUR);
2318                         owner_->getLyXFunc()->setMessage(N_("Mark removed"));
2319                 } else {
2320                         beforeChange(lt);
2321                         lt->selection.mark(true);
2322                         update(lt,
2323                                BufferView::SELECT
2324                                | BufferView::FITCUR);
2325                         owner_->getLyXFunc()->setMessage(N_("Mark set"));
2326                 }
2327                 lt->selection.cursor = lt->cursor;
2328         }
2329         break;
2330                 
2331         case LFUN_DELETE:
2332         {
2333                 LyXText * lt = bv_->getLyXText();
2334
2335                 if (!lt->selection.set()) {
2336                         lt->Delete(bv_);
2337                         lt->selection.cursor = lt->cursor;
2338                         update(lt,
2339                                BufferView::SELECT
2340                                | BufferView::FITCUR
2341                                | BufferView::CHANGE);
2342                         // It is possible to make it a lot faster still
2343                         // just comment out the line below...
2344                         showCursor();
2345                 } else {
2346                         bv_->cut();
2347                 }
2348                 moveCursorUpdate(false);
2349                 owner_->showState();
2350                 setState();
2351         }
2352         break;
2353
2354         case LFUN_DELETE_SKIP:
2355         {
2356                 LyXText * lt = bv_->getLyXText();
2357
2358                 // Reverse the effect of LFUN_BREAKPARAGRAPH_SKIP.
2359                 
2360                 LyXCursor cursor = lt->cursor;
2361
2362                 if (!lt->selection.set()) {
2363                         if (cursor.pos() == cursor.par()->size()) {
2364                                 lt->cursorRight(bv_);
2365                                 cursor = lt->cursor;
2366                                 if (cursor.pos() == 0
2367                                     && !(cursor.par()->params().spaceTop()
2368                                          == VSpace (VSpace::NONE))) {
2369                                         lt->setParagraph
2370                                                 (bv_,
2371                                                  cursor.par()->params().lineTop(),
2372                                                  cursor.par()->params().lineBottom(),
2373                                                  cursor.par()->params().pagebreakTop(), 
2374                                                  cursor.par()->params().pagebreakBottom(),
2375                                                  VSpace(VSpace::NONE), 
2376                                                  cursor.par()->params().spaceBottom(),
2377                                                  cursor.par()->params().align(), 
2378                                                  cursor.par()->params().labelWidthString(), 0);
2379                                         lt->cursorLeft(bv_);
2380                                         update(lt, 
2381                                                BufferView::SELECT
2382                                                | BufferView::FITCUR
2383                                                | BufferView::CHANGE);
2384                                 } else {
2385                                         lt->cursorLeft(bv_);
2386                                         lt->Delete(bv_);
2387                                         lt->selection.cursor = lt->cursor;
2388                                         update(lt,
2389                                                BufferView::SELECT
2390                                                | BufferView::FITCUR
2391                                                | BufferView::CHANGE);
2392                                 }
2393                         } else {
2394                                 lt->Delete(bv_);
2395                                 lt->selection.cursor = lt->cursor;
2396                                 update(lt,
2397                                        BufferView::SELECT
2398                                        | BufferView::FITCUR
2399                                        | BufferView::CHANGE);
2400                         }
2401                 } else {
2402                         bv_->cut();
2403                 }
2404         }
2405         break;
2406
2407         /* -------> Delete word forward. */
2408         case LFUN_DELETE_WORD_FORWARD:
2409                 update(bv_->getLyXText(), BufferView::SELECT|BufferView::FITCUR);
2410                 bv_->getLyXText()->deleteWordForward(bv_);
2411                 update(bv_->getLyXText(), BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2412                 moveCursorUpdate(false);
2413                 owner_->showState();
2414                 break;
2415
2416                 /* -------> Delete word backward. */
2417         case LFUN_DELETE_WORD_BACKWARD:
2418         {
2419                 LyXText * lt = bv_->getLyXText();
2420                 
2421                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2422                 lt->deleteWordBackward(bv_);
2423                 update(lt,
2424                        BufferView::SELECT
2425                        | BufferView::FITCUR
2426                        | BufferView::CHANGE);
2427                 moveCursorUpdate(false);
2428                 owner_->showState();
2429         }
2430         break;
2431                 
2432                 /* -------> Kill to end of line. */
2433         case LFUN_DELETE_LINE_FORWARD:
2434         {
2435                 LyXText * lt = bv_->getLyXText();
2436                 
2437                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2438                 lt->deleteLineForward(bv_);
2439                 update(lt,
2440                        BufferView::SELECT
2441                        | BufferView::FITCUR
2442                        | BufferView::CHANGE);
2443                 moveCursorUpdate(false);
2444         }
2445         break;
2446                 
2447                 /* -------> Set mark off. */
2448         case LFUN_MARK_OFF:
2449         {
2450                 LyXText * lt = bv_->getLyXText();
2451                 
2452                 beforeChange(lt);
2453                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2454                 lt->selection.cursor = lt->cursor;
2455                 owner_->getLyXFunc()->setMessage(N_("Mark off"));
2456         }
2457         break;
2458
2459                 /* -------> Set mark on. */
2460         case LFUN_MARK_ON:
2461         {
2462                 LyXText * lt = bv_->getLyXText();
2463                 
2464                 beforeChange(lt);
2465                 lt->selection.mark(true);
2466                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2467                 lt->selection.cursor = lt->cursor;
2468                 owner_->getLyXFunc()->setMessage(N_("Mark on"));
2469         }
2470         break;
2471                 
2472         case LFUN_BACKSPACE:
2473         {
2474                 LyXText * lt = bv_->getLyXText();
2475                 
2476                 if (!lt->selection.set()) {
2477                         if (owner_->getIntl()->getTrans().backspace()) {
2478                                 lt->backspace(bv_);
2479                                 lt->selection.cursor = lt->cursor;
2480                                 update(lt,
2481                                        BufferView::SELECT
2482                                        | BufferView::FITCUR
2483                                        | BufferView::CHANGE);
2484                                 // It is possible to make it a lot faster still
2485                                 // just comment out the line below...
2486                                 showCursor();
2487                         }
2488                 } else {
2489                         bv_->cut();
2490                 }
2491                 owner_->showState();
2492                 setState();
2493         }
2494         break;
2495
2496         case LFUN_BACKSPACE_SKIP:
2497         {
2498                 // Reverse the effect of LFUN_BREAKPARAGRAPH_SKIP.
2499                 LyXText * lt = bv_->getLyXText();
2500                 
2501                 LyXCursor cursor = lt->cursor;
2502                 
2503                 if (!lt->selection.set()) {
2504                         if (cursor.pos() == 0 
2505                             && !(cursor.par()->params().spaceTop() 
2506                                  == VSpace (VSpace::NONE))) {
2507                                 lt->setParagraph 
2508                                         (bv_,
2509                                          cursor.par()->params().lineTop(),      
2510                                          cursor.par()->params().lineBottom(),
2511                                          cursor.par()->params().pagebreakTop(), 
2512                                          cursor.par()->params().pagebreakBottom(),
2513                                          VSpace(VSpace::NONE), cursor.par()->params().spaceBottom(),
2514                                          cursor.par()->params().align(), 
2515                                          cursor.par()->params().labelWidthString(), 0);
2516                                 update(lt,
2517                                        BufferView::SELECT
2518                                        | BufferView::FITCUR
2519                                        | BufferView::CHANGE);
2520                         } else {
2521                                 lt->backspace(bv_);
2522                                 lt->selection.cursor = cursor;
2523                                 update(lt,
2524                                        BufferView::SELECT
2525                                        | BufferView::FITCUR
2526                                        | BufferView::CHANGE);
2527                         }
2528                 } else
2529                         bv_->cut();
2530         }
2531         break;
2532
2533         case LFUN_BREAKPARAGRAPH:
2534         {
2535                 LyXText * lt = bv_->getLyXText();
2536                 
2537                 beforeChange(lt);
2538                 lt->breakParagraph(bv_, 0);
2539                 update(lt,
2540                        BufferView::SELECT
2541                        | BufferView::FITCUR
2542                        | BufferView::CHANGE);
2543                 lt->selection.cursor = lt->cursor;
2544                 setState();
2545                 owner_->showState();
2546                 break;
2547         }
2548
2549         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
2550         {
2551                 LyXText * lt = bv_->getLyXText();
2552                 
2553                 beforeChange(lt);
2554                 lt->breakParagraph(bv_, 1);
2555                 update(lt,
2556                        BufferView::SELECT
2557                        | BufferView::FITCUR
2558                        | BufferView::CHANGE);
2559                 lt->selection.cursor = lt->cursor;
2560                 setState();
2561                 owner_->showState();
2562                 break;
2563         }
2564         
2565         case LFUN_BREAKPARAGRAPH_SKIP:
2566         {
2567                 // When at the beginning of a paragraph, remove
2568                 // indentation and add a "defskip" at the top.
2569                 // Otherwise, do the same as LFUN_BREAKPARAGRAPH.
2570                 LyXText * lt = bv_->getLyXText();
2571                 
2572                 LyXCursor cursor = lt->cursor;
2573                 
2574                 beforeChange(lt);
2575                 if (cursor.pos() == 0) {
2576                         if (cursor.par()->params().spaceTop() == VSpace(VSpace::NONE)) {
2577                                 lt->setParagraph
2578                                         (bv_,
2579                                          cursor.par()->params().lineTop(),      
2580                                          cursor.par()->params().lineBottom(),
2581                                          cursor.par()->params().pagebreakTop(), 
2582                                          cursor.par()->params().pagebreakBottom(),
2583                                          VSpace(VSpace::DEFSKIP), cursor.par()->params().spaceBottom(),
2584                                          cursor.par()->params().align(), 
2585                                          cursor.par()->params().labelWidthString(), 1);
2586                                 //update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2587                         } 
2588                 }
2589                 else {
2590                         lt->breakParagraph(bv_, 0);
2591                         //update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2592                 }
2593
2594                 update(lt,
2595                        BufferView::SELECT
2596                        | BufferView::FITCUR
2597                        | BufferView::CHANGE);
2598                 lt->selection.cursor = cursor;
2599                 setState();
2600                 owner_->showState();
2601         }
2602         break;
2603
2604         case LFUN_PARAGRAPH_SPACING:
2605         {
2606                 LyXText * lt = bv_->getLyXText();
2607                 
2608                 Paragraph * par = lt->cursor.par();
2609                 Spacing::Space cur_spacing = par->params().spacing().getSpace();
2610                 float cur_value = 1.0;
2611                 if (cur_spacing == Spacing::Other) {
2612                         cur_value = par->params().spacing().getValue();
2613                 }
2614                 
2615                 istringstream istr(argument.c_str());
2616
2617                 string tmp;
2618                 istr >> tmp;
2619                 Spacing::Space new_spacing = cur_spacing;
2620                 float new_value = cur_value;
2621                 if (tmp.empty()) {
2622                         lyxerr << "Missing argument to `paragraph-spacing'"
2623                                << endl;
2624                 } else if (tmp == "single") {
2625                         new_spacing = Spacing::Single;
2626                 } else if (tmp == "onehalf") {
2627                         new_spacing = Spacing::Onehalf;
2628                 } else if (tmp == "double") {
2629                         new_spacing = Spacing::Double;
2630                 } else if (tmp == "other") {
2631                         new_spacing = Spacing::Other;
2632                         float tmpval = 0.0;
2633                         istr >> tmpval;
2634                         lyxerr << "new_value = " << tmpval << endl;
2635                         if (tmpval != 0.0)
2636                                 new_value = tmpval;
2637                 } else if (tmp == "default") {
2638                         new_spacing = Spacing::Default;
2639                 } else {
2640                         lyxerr << _("Unknown spacing argument: ")
2641                                << argument << endl;
2642                 }
2643                 if (cur_spacing != new_spacing || cur_value != new_value) {
2644                         par->params().spacing(Spacing(new_spacing, new_value));
2645                         lt->redoParagraph(bv_);
2646                         update(lt,
2647                                BufferView::SELECT
2648                                | BufferView::FITCUR
2649                                | BufferView::CHANGE);
2650                 }
2651         }
2652         break;
2653         
2654         case LFUN_INSET_TOGGLE:
2655         {
2656                 LyXText * lt = bv_->getLyXText();
2657                 hideCursor();
2658                 beforeChange(lt);
2659                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2660                 lt->toggleInset(bv_);
2661                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2662                 setState();
2663         }       
2664                 break;
2665
2666         case LFUN_QUOTE:
2667                 smartQuote();
2668                 break;
2669
2670         case LFUN_HTMLURL:
2671         case LFUN_URL:
2672         {
2673                 InsetCommandParams p;
2674                 if (action == LFUN_HTMLURL)
2675                         p.setCmdName("htmlurl");
2676                 else
2677                         p.setCmdName("url");
2678                 owner_->getDialogs()->createUrl(p.getAsString());
2679         }
2680         break;
2681         
2682         case LFUN_INSERT_URL:
2683         {
2684                 InsetCommandParams p;
2685                 p.setFromString(argument);
2686
2687                 InsetUrl * inset = new InsetUrl(p);
2688                 if (!insertInset(inset))
2689                         delete inset;
2690                 else
2691                         updateInset(inset, true);
2692         }
2693         break;
2694         
2695         case LFUN_INSET_TEXT:
2696                 insertAndEditInset(new InsetText);
2697                 break;
2698         
2699         case LFUN_INSET_ERT:
2700                 insertAndEditInset(new InsetERT);
2701                 break;
2702         
2703         case LFUN_INSET_EXTERNAL:
2704                 insertAndEditInset(new InsetExternal);
2705                 break;
2706         
2707         case LFUN_INSET_FOOTNOTE:
2708                 insertAndEditInset(new InsetFoot);
2709                 break;
2710
2711         case LFUN_INSET_MARGINAL:
2712                 insertAndEditInset(new InsetMarginal);
2713                 break;
2714
2715         case LFUN_INSET_MINIPAGE:
2716                 insertAndEditInset(new InsetMinipage);
2717                 break;
2718
2719         case LFUN_INSERT_NOTE:
2720                 insertAndEditInset(new InsetNote);
2721                 break;
2722
2723         case LFUN_INSET_FLOAT:
2724                 // check if the float type exist
2725                 if (floatList.typeExist(argument)) {
2726                         insertAndEditInset(new InsetFloat(argument));
2727                 } else {
2728                         lyxerr << "Non-existant float type: "
2729                                << argument << endl;
2730                 }
2731                 break;
2732
2733         case LFUN_INSET_WIDE_FLOAT:
2734         {
2735                 // check if the float type exist
2736                 if (floatList.typeExist(argument)) {
2737                         InsetFloat * new_inset = new InsetFloat(argument);
2738                         new_inset->wide(true);
2739                         if (insertInset(new_inset))
2740                                 new_inset->edit(bv_);
2741                         else
2742                                 delete new_inset;
2743                 } else {
2744                         lyxerr << "Non-existant float type: "
2745                                << argument << endl;
2746                 }
2747                 
2748         }
2749         break;
2750
2751 #if 0
2752         case LFUN_INSET_LIST:
2753                 insertAndEditInset(new InsetList);
2754                 break;
2755
2756         case LFUN_INSET_THEOREM:
2757                 insertAndEditInset(new InsetTheorem);
2758                 break;
2759 #endif
2760                 
2761         case LFUN_INSET_CAPTION:
2762         {
2763                 // Do we have a locking inset...
2764                 if (bv_->theLockingInset()) {
2765                         lyxerr << "Locking inset code: "
2766                                << static_cast<int>(bv_->theLockingInset()->lyxCode());
2767                         InsetCaption * new_inset = new InsetCaption;
2768                         new_inset->setOwner(bv_->theLockingInset());
2769                         new_inset->setAutoBreakRows(true);
2770                         new_inset->setDrawFrame(0, InsetText::LOCKED);
2771                         new_inset->setFrameColor(0, LColor::captionframe);
2772                         if (insertInset(new_inset))
2773                                 new_inset->edit(bv_);
2774                         else
2775                                 delete new_inset;
2776                 }
2777         }
2778         break;
2779         
2780         case LFUN_INSET_TABULAR:
2781         {
2782                 int r = 2;
2783                 int c = 2;
2784                 if (!argument.empty())
2785                         ::sscanf(argument.c_str(),"%d%d", &r, &c);
2786                 InsetTabular * new_inset =
2787                         new InsetTabular(*buffer_, r, c);
2788                 bool const rtl =
2789                         bv_->getLyXText()->real_current_font.isRightToLeft();
2790                 if (!open_new_inset(new_inset, rtl))
2791                         delete new_inset;
2792         }
2793         break;
2794
2795         // --- lyxserver commands ----------------------------
2796
2797         case LFUN_CHARATCURSOR:
2798         {
2799                 Paragraph::size_type pos = bv_->getLyXText()->cursor.pos();
2800                 if (pos < bv_->getLyXText()->cursor.par()->size())
2801                         owner_->getLyXFunc()->setMessage(
2802                                 tostr(bv_->getLyXText()->cursor.par()->getChar(pos)));
2803                 else
2804                         owner_->getLyXFunc()->setMessage("EOF");
2805         }
2806         break;
2807         
2808         case LFUN_GETXY:
2809                 owner_->getLyXFunc()->setMessage(tostr(bv_->getLyXText()->cursor.x())
2810                                                  + ' '
2811                                                  + tostr(bv_->getLyXText()->cursor.y()));
2812                 break;
2813                 
2814         case LFUN_SETXY:
2815         {
2816                 int x = 0;
2817                 int y = 0;
2818                 if (::sscanf(argument.c_str(), " %d %d", &x, &y) != 2) {
2819                         lyxerr << "SETXY: Could not parse coordinates in '"
2820                                << argument << std::endl;
2821                 }
2822                 bv_->getLyXText()->setCursorFromCoordinates(bv_, x, y);
2823         }
2824         break;
2825         
2826         case LFUN_GETLAYOUT:
2827                 owner_->getLyXFunc()->setMessage(tostr(bv_->getLyXText()->cursor.par()->layout));
2828                 break;
2829                         
2830         case LFUN_GETFONT:
2831         {
2832                 LyXFont & font = bv_->getLyXText()->current_font;
2833                 if (font.shape() == LyXFont::ITALIC_SHAPE)
2834                         owner_->getLyXFunc()->setMessage("E");
2835                 else if (font.shape() == LyXFont::SMALLCAPS_SHAPE)
2836                         owner_->getLyXFunc()->setMessage("N");
2837                 else
2838                         owner_->getLyXFunc()->setMessage("0");
2839
2840         }
2841         break;
2842
2843         case LFUN_GETLATEX:
2844         {
2845 #ifndef NO_LATEX
2846                 LyXFont & font = bv_->getLyXText()->current_font;
2847                 if (font.latex() == LyXFont::ON)
2848                         owner_->getLyXFunc()->setMessage("L");
2849                 else
2850 #endif
2851                         owner_->getLyXFunc()->setMessage("0");
2852         }
2853         break;
2854
2855         // --- accented characters ---------------------------
2856                 
2857         case LFUN_UMLAUT:
2858         case LFUN_CIRCUMFLEX:
2859         case LFUN_GRAVE:
2860         case LFUN_ACUTE:
2861         case LFUN_TILDE:
2862         case LFUN_CEDILLA:
2863         case LFUN_MACRON:
2864         case LFUN_DOT:
2865         case LFUN_UNDERDOT:
2866         case LFUN_UNDERBAR:
2867         case LFUN_CARON:
2868         case LFUN_SPECIAL_CARON:
2869         case LFUN_BREVE:
2870         case LFUN_TIE:
2871         case LFUN_HUNG_UMLAUT:
2872         case LFUN_CIRCLE:
2873         case LFUN_OGONEK:
2874                 if (argument.empty()) {
2875                         // As always...
2876                         owner_->getLyXFunc()->handleKeyFunc(action);
2877                 } else {
2878                         owner_->getLyXFunc()->handleKeyFunc(action);
2879                         owner_->getIntl()->getTrans()
2880                                 .TranslateAndInsert(argument[0], bv_->getLyXText());
2881                         update(bv_->getLyXText(),
2882                                BufferView::SELECT
2883                                | BufferView::FITCUR
2884                                | BufferView::CHANGE);
2885                 }
2886                 break;
2887         
2888         case LFUN_MATH_MACRO:
2889                 mathDispatchMathMacro(bv_, argument);
2890                 break;
2891
2892         case LFUN_MATH_DELIM:     
2893                 mathDispatchMathDelim(bv_, argument);
2894                 break;
2895
2896         case LFUN_INSERT_MATRIX:
2897                 mathDispatchInsertMatrix(bv_, argument);
2898                 break;
2899
2900         case LFUN_INSERT_MATH:
2901                 mathDispatchInsertMath(bv_, argument);
2902                 break;
2903
2904         case LFUN_MATH_IMPORT_SELECTION: // Imports LaTeX from the X selection
2905                 mathDispatchMathImportSelection(bv_, argument);
2906                 break;
2907
2908         case LFUN_MATH_DISPLAY:          // Open or create a displayed math inset
2909                 mathDispatchMathDisplay(bv_, argument);
2910                 break;
2911
2912         case LFUN_MATH_MODE:             // Open or create an inlined math inset 
2913                 mathDispatchMathMode(bv_, argument);
2914                 break;
2915                 
2916         case LFUN_CITATION_INSERT:
2917         {
2918                 InsetCommandParams p;
2919                 p.setFromString( argument );
2920
2921                 InsetCitation * inset = new InsetCitation( p );
2922                 if (!insertInset(inset))
2923                         delete inset;
2924                 else
2925                         updateInset( inset, true );
2926         }
2927         break;
2928                     
2929         case LFUN_INSERT_BIBTEX:
2930         {   
2931                 // ale970405+lasgoutt970425
2932                 // The argument can be up to two tokens separated 
2933                 // by a space. The first one is the bibstyle.
2934                 string const db       = token(argument, ' ', 0);
2935                 string bibstyle = token(argument, ' ', 1);
2936                 if (bibstyle.empty())
2937                         bibstyle = "plain";
2938
2939                 InsetCommandParams p( "BibTeX", db, bibstyle );
2940                 InsetBibtex * inset = new InsetBibtex(p);
2941                 
2942                 if (insertInset(inset)) {
2943                         if (argument.empty())
2944                                 inset->edit(bv_);
2945                 } else
2946                         delete inset;
2947         }
2948         break;
2949                 
2950         // BibTeX data bases
2951         case LFUN_BIBDB_ADD:
2952         {
2953                 InsetBibtex * inset = 
2954                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
2955                 if (inset) {
2956                         inset->addDatabase(argument);
2957                 }
2958         }
2959         break;
2960                     
2961         case LFUN_BIBDB_DEL:
2962         {
2963                 InsetBibtex * inset = 
2964                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
2965                 if (inset) {
2966                         inset->delDatabase(argument);
2967                 }
2968         }
2969         break;
2970         
2971         case LFUN_BIBTEX_STYLE:
2972         {
2973                 InsetBibtex * inset = 
2974                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
2975                 if (inset) {
2976                         inset->setOptions(argument);
2977                 }
2978         }
2979         break;
2980                 
2981         case LFUN_INDEX_CREATE:
2982         {
2983                 InsetCommandParams p("index");
2984                 LyXText * lt = bv_->getLyXText();
2985                 
2986                 if (argument.empty()) {
2987                         string const idxstring(bv_->getLyXText()->getStringToIndex(bv_));
2988                         if (!idxstring.empty()) 
2989                                 p.setContents(idxstring);
2990                         else
2991                                 break;
2992                 } else {
2993                         p.setContents(argument);
2994                 }
2995
2996                 owner_->getDialogs()->createIndex(p.getAsString());
2997         }
2998         break;
2999                     
3000         case LFUN_INDEX_INSERT:
3001         {
3002                 InsetCommandParams p;
3003                 p.setFromString(argument);
3004                 InsetIndex * inset = new InsetIndex(p);
3005
3006                 if (!insertInset(inset))
3007                         delete inset;
3008                 else
3009                         updateInset(inset, true);
3010         }
3011         break;
3012                     
3013         case LFUN_INDEX_INSERT_LAST:
3014         {
3015                 string const idxstring(bv_->getLyXText()->getStringToIndex(bv_));
3016                 if (!idxstring.empty()) {
3017                         owner_->message(_("Word `")
3018                                         + idxstring + _(("' indexed.")));
3019                         InsetCommandParams p("index", idxstring);
3020                         InsetIndex * inset = new InsetIndex(p);
3021                         
3022                         if (!insertInset(inset))
3023                                 delete inset;
3024                         else
3025                                 updateInset(inset, true);
3026                 }
3027         }
3028         break;
3029
3030         case LFUN_INDEX_PRINT:
3031         {
3032                 InsetCommandParams p("printindex");
3033                 Inset * inset = new InsetPrintIndex(p);
3034                 if (!insertInset(inset, "Standard"))
3035                         delete inset;
3036         }
3037         break;
3038
3039         case LFUN_PARENTINSERT:
3040         {
3041                 lyxerr << "arg " << argument << endl;
3042                 InsetCommandParams p( "lyxparent", argument );
3043                 Inset * inset = new InsetParent(p, *buffer_);
3044                 if (!insertInset(inset, "Standard"))
3045                         delete inset;
3046         }
3047                  
3048         break;
3049
3050         case LFUN_CHILD_INSERT:
3051         {
3052                 InsetInclude::Params p;
3053                 p.cparams.setFromString(argument);
3054                 p.masterFilename_ = buffer_->fileName();
3055
3056                 InsetInclude * inset = new InsetInclude(p);
3057                 if (!insertInset(inset))
3058                         delete inset;
3059                 else {
3060                         updateInset(inset, true);
3061                         bv_->owner()->getDialogs()->showInclude(inset);
3062                 }
3063         }
3064         break; 
3065
3066         case LFUN_FLOAT_LIST:
3067         {
3068                 // We should check the argument for validity. (Lgb)
3069                 Inset * inset = new InsetFloatList(argument);
3070                 if (!insertInset(inset, "Standard"))
3071                         delete inset;
3072         }
3073         break;
3074         
3075         case LFUN_THESAURUS_ENTRY:
3076         {
3077                 string arg = argument;
3078
3079                 if (arg.empty()) {
3080                         arg = bv_->getLyXText()->selectionAsString(buffer_);
3081  
3082                         // FIXME
3083                         if (arg.size() > 100 || arg.empty()) {
3084                                 // Get word or selection
3085                                 bv_->getLyXText()->selectWordWhenUnderCursor(bv_, LyXText::WHOLE_WORD);
3086                                 arg = bv_->getLyXText()->selectionAsString(buffer_);
3087                                 // FIXME: where is getLyXText()->unselect(bv_) ?
3088                         }
3089                 }
3090
3091                 bv_->owner()->getDialogs()->showThesaurus(arg);
3092         }
3093                 break;
3094  
3095         case LFUN_SELFINSERT:
3096         {
3097                 if (argument.empty()) break;
3098                 
3099                 /* Automatically delete the currently selected
3100                  * text and replace it with what is being
3101                  * typed in now. Depends on lyxrc settings
3102                  * "auto_region_delete", which defaults to
3103                  * true (on). */
3104
3105                 LyXText * lt = bv_->getLyXText();
3106                 
3107                 if (lyxrc.auto_region_delete) {
3108                         if (lt->selection.set()) {
3109                                 lt->cutSelection(bv_, false);
3110                                 bv_->update(lt,
3111                                             BufferView::SELECT
3112                                             | BufferView::FITCUR
3113                                             | BufferView::CHANGE);
3114                         }
3115                 }
3116                 
3117                 beforeChange(lt);
3118                 LyXFont const old_font(lt->real_current_font);
3119                 
3120                 string::const_iterator cit = argument.begin();
3121                 string::const_iterator end = argument.end();
3122                 for (; cit != end; ++cit) {
3123                         if (greek_kb_flag) {
3124                                 if (!math_insert_greek(bv_, *cit))
3125                                         owner_->getIntl()->getTrans().TranslateAndInsert(*cit, lt);
3126                         } else
3127                                 owner_->getIntl()->getTrans().TranslateAndInsert(*cit, lt);
3128                 }
3129                 
3130                 bv_->update(lt,
3131                             BufferView::SELECT
3132                             | BufferView::FITCUR
3133                             | BufferView::CHANGE);
3134                 
3135                 lt->selection.cursor = lt->cursor;
3136                 moveCursorUpdate(false);
3137                 
3138                 // real_current_font.number can change so we need to
3139                 // update the minibuffer
3140                 if (old_font != lt->real_current_font)
3141                         owner_->showState();
3142                 //return string();
3143         }
3144         break;
3145
3146         case LFUN_DATE_INSERT:  // jdblair: date-insert cmd
3147         {
3148                 time_t now_time_t = time(NULL);
3149                 struct tm * now_tm = localtime(&now_time_t);
3150                 setlocale(LC_TIME, "");
3151                 string arg;
3152                 if (!argument.empty())
3153                         arg = argument;
3154                 else 
3155                         arg = lyxrc.date_insert_format;
3156                 char datetmp[32];
3157                 int const datetmp_len =
3158                         ::strftime(datetmp, 32, arg.c_str(), now_tm);
3159
3160                 LyXText * lt = bv_->getLyXText();
3161                 
3162                 for (int i = 0; i < datetmp_len; i++) {
3163                         lt->insertChar(bv_, datetmp[i]);
3164                         update(lt,
3165                                BufferView::SELECT
3166                                | BufferView::FITCUR
3167                                | BufferView::CHANGE);
3168                 }
3169
3170                 lt->selection.cursor = lt->cursor;
3171                 moveCursorUpdate(false);
3172         }
3173         break;
3174
3175         case LFUN_UNKNOWN_ACTION:
3176                 owner_->getLyXFunc()->setErrorMessage(N_("Unknown function!"));
3177                 break;
3178         
3179         default:
3180                 return false;
3181         } // end of switch
3182
3183         return true;
3184 }
3185
3186
3187 void BufferView::Pimpl::newline()
3188 {
3189         if (available()) {
3190                 LyXText * lt = bv_->getLyXText();
3191                 hideCursor();
3192                 update(lt,
3193                        BufferView::SELECT
3194                        | BufferView::FITCUR);
3195                 lt->insertChar(bv_, Paragraph::META_NEWLINE);
3196                 update(lt,
3197                        BufferView::SELECT
3198                        | BufferView::FITCUR
3199                        | BufferView::CHANGE);
3200         }
3201 }
3202
3203
3204 void BufferView::Pimpl::hfill()
3205 {
3206         if (available()) {
3207                 LyXText * lt = bv_->getLyXText();
3208                 hideCursor();
3209                 update(lt,
3210                        BufferView::SELECT
3211                        | BufferView::FITCUR);
3212                 lt->insertChar(bv_, Paragraph::META_HFILL);
3213                 update(lt,
3214                        BufferView::SELECT
3215                        | BufferView::FITCUR
3216                        | BufferView::CHANGE);
3217         }
3218 }
3219
3220
3221 void BufferView::Pimpl::protectedBlank(LyXText * lt)
3222 {
3223         if (available()) {
3224                 hideCursor();
3225                 update(lt, BufferView::SELECT|BufferView::FITCUR);
3226                 InsetSpecialChar * new_inset =
3227                         new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
3228 #ifdef WITH_WARNINGS
3229 #warning Why is this code different from specialChar() below? (JMarc)
3230 // the code in specialChar is a generic version of what used to exist
3231 // for other special chars. I did not merge this case because of the
3232 // call to updateInset(), but what does it do?
3233 #endif
3234                 if (!insertInset(new_inset))
3235                         delete new_inset;
3236                 else
3237                         updateInset(new_inset, true);
3238         }
3239 }
3240
3241
3242 void BufferView::Pimpl::specialChar(InsetSpecialChar::Kind kind)
3243 {
3244         if (available()) {
3245                 LyXText * lt = bv_->getLyXText();
3246                 
3247                 hideCursor();
3248                 update(lt, BufferView::SELECT|BufferView::FITCUR);
3249                 InsetSpecialChar * new_inset = 
3250                         new InsetSpecialChar(kind);
3251                 insertInset(new_inset);
3252         }
3253 }
3254
3255
3256 void BufferView::Pimpl::smartQuote()
3257 {
3258         char c;
3259         LyXText * lt = bv_->getLyXText();
3260
3261         if (lt->cursor.pos())
3262                 c = lt->cursor.par()->getChar(lt->cursor.pos() - 1);
3263         else 
3264                 c = ' ';
3265
3266         hideCursor();
3267         if (!insertInset(new InsetQuotes(c, bv_->buffer()->params)))
3268                 Dispatch(LFUN_SELFINSERT, "\"");
3269 }
3270
3271
3272 void BufferView::Pimpl::insertAndEditInset(Inset * inset)
3273 {
3274         if (insertInset(inset))
3275                 inset->edit(bv_);
3276         else
3277                 delete inset;
3278 }
3279
3280  
3281 // Open and lock an updatable inset
3282 bool BufferView::Pimpl::open_new_inset(UpdatableInset * new_inset, bool behind)
3283 {
3284         LyXText * lt = bv_->getLyXText();
3285         
3286         beforeChange(lt);
3287         finishUndo();
3288         if (!insertInset(new_inset)) {
3289                 delete new_inset;
3290                 return false;
3291         }
3292         new_inset->edit(bv_, !behind);
3293         return true;
3294 }
3295
3296
3297 bool BufferView::Pimpl::insertInset(Inset * inset, string const & lout)
3298 {
3299         // if we are in a locking inset we should try to insert the
3300         // inset there otherwise this is a illegal function now
3301         if (bv_->theLockingInset()) {
3302                 if (bv_->theLockingInset()->insetAllowed(inset))
3303                     return bv_->theLockingInset()->insertInset(bv_, inset);
3304                 return false;
3305         }
3306
3307         // not quite sure if we want this...
3308         setCursorParUndo(bv_);
3309         freezeUndo();
3310         
3311         beforeChange(bv_->text);
3312         if (!lout.empty()) {
3313                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
3314                 bv_->text->breakParagraph(bv_);
3315                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3316
3317                 if (bv_->text->cursor.par()->size()) {
3318                         bv_->text->cursorLeft(bv_);
3319                         
3320                         bv_->text->breakParagraph(bv_);
3321                         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3322                 }
3323
3324                 pair<bool, LyXTextClass::size_type> lres =
3325                         textclasslist.NumberOfLayout(buffer_->params
3326                                                      .textclass, lout);
3327                 LyXTextClass::size_type lay;
3328                 if (lres.first != false) {
3329                         // layout found
3330                         lay = lres.second;
3331                 } else {
3332                         // layout not fount using default "Standard" (0)
3333                         lay = 0;
3334                 }
3335                  
3336                 bv_->text->setLayout(bv_, lay);
3337                 
3338                 bv_->text->setParagraph(bv_, 0, 0,
3339                                    0, 0,
3340                                    VSpace(VSpace::NONE), VSpace(VSpace::NONE),
3341                                    LYX_ALIGN_LAYOUT, 
3342                                    string(),
3343                                    0);
3344                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3345 #ifndef NO_LATEX
3346                 bv_->text->current_font.setLatex(LyXFont::OFF);
3347 #endif
3348         }
3349         
3350         bv_->text->insertInset(bv_, inset);
3351         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3352
3353         unFreezeUndo();
3354         return true;
3355 }
3356
3357
3358 void BufferView::Pimpl::updateInset(Inset * inset, bool mark_dirty)
3359 {
3360         if (!inset)
3361                 return;
3362
3363         // first check for locking insets
3364         if (bv_->theLockingInset()) {
3365                 if (bv_->theLockingInset() == inset) {
3366                         if (bv_->text->updateInset(bv_, inset)) {
3367                                 update();
3368                                 if (mark_dirty) {
3369                                         buffer_->markDirty();
3370                                 }
3371                                 updateScrollbar();
3372                                 return;
3373                         }
3374                 } else if (bv_->theLockingInset()->updateInsetInInset(bv_, inset)) {
3375                         if (bv_->text->updateInset(bv_,
3376                                                    bv_->theLockingInset())) {
3377                                 update();
3378                                 if (mark_dirty){
3379                                         buffer_->markDirty();
3380                                 }
3381                                 updateScrollbar();
3382                                 return;
3383                         }
3384                 }
3385         }
3386   
3387         // then check the current buffer
3388         if (available()) {
3389                 hideCursor();
3390                 update(bv_->text, BufferView::UPDATE);
3391                 if (bv_->text->updateInset(bv_, inset)) {
3392                         if (mark_dirty) {
3393                                 update(bv_->text,
3394                                        BufferView::SELECT
3395                                        | BufferView::FITCUR
3396                                        | BufferView::CHANGE);
3397                         } else {
3398                                 update(bv_->text, SELECT);
3399                         }
3400                         return;
3401                 }
3402         }
3403 }
3404
3405
3406 void BufferView::Pimpl::gotoInset(vector<Inset::Code> const & codes,
3407                                   bool same_content)
3408 {
3409         if (!available()) return;
3410         
3411         hideCursor();
3412         beforeChange(bv_->text);
3413         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
3414         
3415         string contents;
3416         if (same_content &&
3417             bv_->text->cursor.par()->getChar(bv_->text->cursor.pos()) == Paragraph::META_INSET) {
3418                 Inset const * inset = bv_->text->cursor.par()->getInset(bv_->text->cursor.pos());
3419                 if (find(codes.begin(), codes.end(), inset->lyxCode())
3420                     != codes.end())
3421                         contents =
3422                                 static_cast<InsetCommand const *>(inset)->getContents();
3423         }
3424         
3425         if (!bv_->text->gotoNextInset(bv_, codes, contents)) {
3426                 if (bv_->text->cursor.pos() 
3427                     || bv_->text->cursor.par() != bv_->text->firstParagraph()) {
3428                         LyXCursor tmp = bv_->text->cursor;
3429                         bv_->text->cursor.par(bv_->text->firstParagraph());
3430                         bv_->text->cursor.pos(0);
3431                         if (!bv_->text->gotoNextInset(bv_, codes, contents)) {
3432                                 bv_->text->cursor = tmp;
3433                                 bv_->owner()->message(_("No more insets"));
3434                         }
3435                 } else {
3436                         bv_->owner()->message(_("No more insets"));
3437                 }
3438         }
3439         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
3440         bv_->text->selection.cursor = bv_->text->cursor;
3441 }
3442
3443
3444 void BufferView::Pimpl::gotoInset(Inset::Code code, bool same_content)
3445 {
3446         gotoInset(vector<Inset::Code>(1, code), same_content);
3447 }