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