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