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