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