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