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