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