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