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