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