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