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