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