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