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