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