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