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