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