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