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