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