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