]> git.lyx.org Git - lyx.git/blob - src/BufferView_pimpl.C
the optional argument patch from martin
[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 "funcrequest.h"
43 #include "language.h"
44
45 #include "insets/insetbib.h"
46 #include "insets/insettext.h"
47 #include "insets/inseturl.h"
48 #include "insets/insetlatexaccent.h"
49 #include "insets/insettoc.h"
50 #include "insets/insetref.h"
51 #include "insets/insetparent.h"
52 #include "insets/insetindex.h"
53 #include "insets/insetnote.h"
54 #include "insets/insetinclude.h"
55 #include "insets/insetcite.h"
56 #include "insets/insetert.h"
57 #include "insets/insetexternal.h"
58 #include "insets/insetgraphics.h"
59 #include "insets/insetfoot.h"
60 #include "insets/insetmarginal.h"
61 #include "insets/insetminipage.h"
62 #include "insets/insetfloat.h"
63 #include "insets/insettabular.h"
64 #include "insets/insetoptarg.h"
65 #if 0
66 #include "insets/insettheorem.h"
67 #include "insets/insetlist.h"
68 #endif
69 #include "insets/insetcaption.h"
70 #include "insets/insetfloatlist.h"
71
72 #include "mathed/formulabase.h"
73
74 #include "graphics/Previews.h"
75
76 #include "support/LAssert.h"
77 #include "support/lstrings.h"
78 #include "support/filetools.h"
79 #include "support/lyxfunctional.h"
80
81 #include <boost/bind.hpp>
82 #include <boost/signals/connection.hpp>
83
84 #include <cstdio>
85 #include <ctime>
86 #include <unistd.h>
87 #include <sys/wait.h>
88 #include <clocale>
89
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 unsigned int const saved_positions_num = 20;
123
124 // All the below connection objects are needed because of a bug in some
125 // versions of GCC (<=2.96 are on the suspects list.) By having and assigning
126 // to these connections we avoid a segfault upon startup, and also at exit.
127 // (Lgb)
128
129 boost::signals::connection timecon;
130 boost::signals::connection doccon;
131 boost::signals::connection resizecon;
132 boost::signals::connection bpresscon;
133 boost::signals::connection breleasecon;
134 boost::signals::connection motioncon;
135 boost::signals::connection doublecon;
136 boost::signals::connection triplecon;
137 boost::signals::connection kpresscon;
138 boost::signals::connection selectioncon;
139 boost::signals::connection lostcon;
140
141 } // anon namespace
142
143
144 BufferView::Pimpl::Pimpl(BufferView * bv, LyXView * owner,
145              int xpos, int ypos, int width, int height)
146         : bv_(bv), owner_(owner), buffer_(0), cursor_timeout(400),
147           using_xterm_cursor(false)
148 {
149         workarea_.reset(WorkAreaFactory::create(xpos, ypos, width, height));
150         screen_.reset(LyXScreenFactory::create(workarea()));
151
152         // Setup the signals
153         doccon = workarea().scrollDocView
154                 .connect(boost::bind(&BufferView::Pimpl::scrollDocView, this, _1));
155         resizecon = workarea().workAreaResize
156                 .connect(boost::bind(&BufferView::Pimpl::workAreaResize, this));
157         bpresscon = workarea().workAreaButtonPress
158                 .connect(boost::bind(&BufferView::Pimpl::workAreaButtonPress, this, _1, _2, _3));
159         breleasecon = workarea().workAreaButtonRelease
160                 .connect(boost::bind(&BufferView::Pimpl::workAreaButtonRelease, this, _1, _2, _3));
161         motioncon = workarea().workAreaMotionNotify
162                 .connect(boost::bind(&BufferView::Pimpl::workAreaMotionNotify, this, _1, _2, _3));
163         doublecon = workarea().workAreaDoubleClick
164                 .connect(boost::bind(&BufferView::Pimpl::doubleClick, this, _1, _2, _3));
165         triplecon = workarea().workAreaTripleClick
166                 .connect(boost::bind(&BufferView::Pimpl::tripleClick, this, _1, _2, _3));
167         kpresscon = workarea().workAreaKeyPress
168                 .connect(boost::bind(&BufferView::Pimpl::workAreaKeyPress, this, _1, _2));
169         selectioncon = workarea().selectionRequested
170                 .connect(boost::bind(&BufferView::Pimpl::selectionRequested, this));
171         lostcon = workarea().selectionLost
172                 .connect(boost::bind(&BufferView::Pimpl::selectionLost, this));
173
174         timecon = cursor_timeout.timeout
175                 .connect(boost::bind(&BufferView::Pimpl::cursorToggle, this));
176         cursor_timeout.start();
177         saved_positions.resize(saved_positions_num);
178 }
179
180
181 WorkArea & BufferView::Pimpl::workarea() const
182 {
183         return *workarea_.get();
184 }
185
186
187 LyXScreen & BufferView::Pimpl::screen() const
188 {
189         return *screen_.get();
190 }
191
192
193 Painter & BufferView::Pimpl::painter() const
194 {
195         return workarea().getPainter();
196 }
197
198
199 void BufferView::Pimpl::buffer(Buffer * b)
200 {
201         lyxerr[Debug::INFO] << "Setting buffer in BufferView ("
202                             << b << ")" << endl;
203         if (buffer_) {
204                 buffer_->delUser(bv_);
205
206                 // Put the old text into the TextCache, but
207                 // only if the buffer is still loaded.
208                 // Also set the owner of the test to 0
209                 //              bv_->text->owner(0);
210                 textcache.add(buffer_, workarea().workWidth(), bv_->text);
211                 if (lyxerr.debugging())
212                         textcache.show(lyxerr, "BufferView::buffer");
213
214                 bv_->text = 0;
215         }
216
217         // set current buffer
218         buffer_ = b;
219
220         if (bufferlist.getState() == BufferList::CLOSING) return;
221
222         // if we are closing the buffer, use the first buffer as current
223         if (!buffer_) {
224                 buffer_ = bufferlist.first();
225         }
226
227         if (buffer_) {
228                 lyxerr[Debug::INFO] << "Buffer addr: " << buffer_ << endl;
229                 buffer_->addUser(bv_);
230
231                 // If we don't have a text object for this, we make one
232                 if (bv_->text == 0) {
233                         resizeCurrentBuffer();
234                 }
235
236                 // FIXME: needed when ?
237                 bv_->text->first_y =
238                         screen().topCursorVisible(bv_->text->cursor, bv_->text->first_y);
239
240                 // Similarly, buffer-dependent dialogs should be updated or
241                 // hidden. This should go here because some dialogs (eg ToC)
242                 // require bv_->text.
243                 owner_->getDialogs().updateBufferDependent(true);
244         } else {
245                 lyxerr[Debug::INFO] << "  No Buffer!" << endl;
246                 owner_->getDialogs().hideBufferDependent();
247
248                 // Also remove all remaining text's from the testcache.
249                 // (there should not be any!) (if there is any it is a
250                 // bug!)
251                 if (lyxerr.debugging())
252                         textcache.show(lyxerr, "buffer delete all");
253                 textcache.clear();
254         }
255
256         repaint();
257         updateScrollbar();
258         owner_->updateMenubar();
259         owner_->updateToolbar();
260         owner_->updateLayoutChoice();
261         owner_->updateWindowTitle();
262
263         if (grfx::Previews::activated() && buffer_)
264                 grfx::Previews::get().generateBufferPreviews(*buffer_);
265 }
266
267
268 bool BufferView::Pimpl::fitCursor()
269 {
270         bool ret;
271
272         if (bv_->theLockingInset()) {
273                 bv_->theLockingInset()->fitInsetCursor(bv_);
274                 ret = true;
275         } else {
276                 ret = screen().fitCursor(bv_->text, bv_);
277         }
278
279         bv_->owner()->getDialogs().updateParagraph();
280         if (ret)
281                 updateScrollbar();
282         return ret;
283 }
284
285
286 void BufferView::Pimpl::redoCurrentBuffer()
287 {
288         lyxerr[Debug::INFO] << "BufferView::redoCurrentBuffer" << endl;
289         if (buffer_ && bv_->text) {
290                 resizeCurrentBuffer();
291                 updateScrollbar();
292                 owner_->updateLayoutChoice();
293                 repaint();
294         }
295 }
296
297
298 int BufferView::Pimpl::resizeCurrentBuffer()
299 {
300         lyxerr[Debug::INFO] << "resizeCurrentBuffer" << endl;
301
302         Paragraph * par = 0;
303         Paragraph * selstartpar = 0;
304         Paragraph * selendpar = 0;
305         UpdatableInset * the_locking_inset = 0;
306
307         pos_type pos = 0;
308         pos_type selstartpos = 0;
309         pos_type selendpos = 0;
310         bool selection = false;
311         bool mark_set  = false;
312
313         owner_->prohibitInput();
314
315         owner_->message(_("Formatting document..."));
316
317         if (bv_->text) {
318                 par = bv_->text->cursor.par();
319                 pos = bv_->text->cursor.pos();
320                 selstartpar = bv_->text->selection.start.par();
321                 selstartpos = bv_->text->selection.start.pos();
322                 selendpar = bv_->text->selection.end.par();
323                 selendpos = bv_->text->selection.end.pos();
324                 selection = bv_->text->selection.set();
325                 mark_set = bv_->text->selection.mark();
326                 the_locking_inset = bv_->theLockingInset();
327                 buffer_->resizeInsets(bv_);
328                 // I don't think the delete and new are necessary here we just could
329                 // call only init! (Jug 20020419)
330                 delete bv_->text;
331                 bv_->text = new LyXText(bv_);
332                 bv_->text->init(bv_);
333         } else {
334                 // See if we have a text in TextCache that fits
335                 // the new buffer_ with the correct width.
336                 bv_->text = textcache.findFit(buffer_, workarea().workWidth());
337                 if (bv_->text) {
338                         if (lyxerr.debugging()) {
339                                 lyxerr << "Found a LyXText that fits:\n";
340                                 textcache.show(lyxerr, make_pair(buffer_, make_pair(workarea().workWidth(), bv_->text)));
341                         }
342                         // Set the owner of the newly found text
343                         //      bv_->text->owner(bv_);
344                         if (lyxerr.debugging())
345                                 textcache.show(lyxerr, "resizeCurrentBuffer");
346                 } else {
347                         bv_->text = new LyXText(bv_);
348                         bv_->text->init(bv_);
349                         //buffer_->resizeInsets(bv_);
350                 }
351         }
352
353         if (par) {
354                 bv_->text->selection.set(true);
355                 // At this point just to avoid the Delete-Empty-Paragraph-
356                 // Mechanism when setting the cursor.
357                 bv_->text->selection.mark(mark_set);
358                 if (selection) {
359                         bv_->text->setCursor(bv_, selstartpar, selstartpos);
360                         bv_->text->selection.cursor = bv_->text->cursor;
361                         bv_->text->setCursor(bv_, selendpar, selendpos);
362                         bv_->text->setSelection(bv_);
363                         bv_->text->setCursor(bv_, par, pos);
364                 } else {
365                         bv_->text->setCursor(bv_, par, pos);
366                         bv_->text->selection.cursor = bv_->text->cursor;
367                         bv_->text->selection.set(false);
368                 }
369                 // remake the inset locking
370                 bv_->theLockingInset(the_locking_inset);
371         }
372
373         bv_->text->first_y = screen().topCursorVisible(bv_->text->cursor, bv_->text->first_y);
374
375         switchKeyMap();
376         owner_->allowInput();
377
378         updateScrollbar();
379
380         return 0;
381 }
382
383
384 void BufferView::Pimpl::repaint()
385 {
386         // Regenerate the screen.
387         screen().redraw(bv_->text, bv_);
388 }
389
390
391 void BufferView::Pimpl::updateScrollbar()
392 {
393         if (!bv_->text) {
394                 lyxerr[Debug::GUI] << "no text in updateScrollbar" << endl;
395                 workarea().setScrollbarParams(0, 0, 0);
396                 return;
397         }
398
399         LyXText const & t = *bv_->text;
400
401         lyxerr[Debug::GUI] << "Updating scrollbar: h " << t.height << ", first_y "
402                 << t.first_y << ", default height " << t.defaultHeight() << endl;
403
404         workarea().setScrollbarParams(t.height, t.first_y, t.defaultHeight());
405 }
406
407
408 void BufferView::Pimpl::scrollDocView(int value)
409 {
410         lyxerr[Debug::GUI] << "scrollDocView of " << value << endl;
411
412         if (!buffer_) return;
413
414         screen().draw(bv_->text, bv_, value);
415
416         if (!lyxrc.cursor_follows_scrollbar) {
417                 return;
418         }
419
420         LyXText * vbt = bv_->text;
421
422         int const height = vbt->defaultHeight();
423         int const first = static_cast<int>((bv_->text->first_y + height));
424         int const last = static_cast<int>((bv_->text->first_y + workarea().workHeight() - height));
425
426         if (vbt->cursor.y() < first)
427                 vbt->setCursorFromCoordinates(bv_, 0, first);
428         else if (vbt->cursor.y() > last)
429                 vbt->setCursorFromCoordinates(bv_, 0, last);
430 }
431
432
433 int BufferView::Pimpl::scroll(long time)
434 {
435         if (!buffer_)
436                 return 0;
437
438         LyXText const * t = bv_->text;
439
440         double const diff = t->defaultHeight()
441                 + double(time) * double(time) * 0.125;
442
443         scrollDocView(int(diff));
444         workarea().setScrollbarParams(t->height, t->first_y, t->defaultHeight());
445         return 0;
446 }
447
448
449 void BufferView::Pimpl::workAreaKeyPress(LyXKeySymPtr key,
450                                          key_modifier::state state)
451 {
452         bv_->owner()->getLyXFunc().processKeySym(key, state);
453 }
454
455
456 void BufferView::Pimpl::workAreaMotionNotify(int x, int y, mouse_button::state state)
457 {
458         // Only use motion with button 1
459         if (!(state & mouse_button::button1))
460                 return;
461
462         if (!buffer_)
463                 return;
464
465         // Check for inset locking
466         if (bv_->theLockingInset()) {
467                 LyXCursor cursor = bv_->text->cursor;
468                 LyXFont font = bv_->text->getFont(buffer_,
469                                                   cursor.par(), cursor.pos());
470                 int width = bv_->theLockingInset()->width(bv_, font);
471                 int inset_x = font.isVisibleRightToLeft()
472                         ? cursor.ix() - width : cursor.ix();
473                 int start_x = inset_x + bv_->theLockingInset()->scroll();
474
475                 FuncRequest cmd(bv_, LFUN_MOUSE_MOTION,
476                                   x - start_x, y - cursor.iy() + bv_->text->first_y, state);
477                 bv_->theLockingInset()->localDispatch(cmd);
478                 return;
479         }
480
481         // The test for not selection possible is needed, that only motion
482         // events are used, where the bottom press event was on
483         //  the drawing area too
484         if (!selection_possible)
485                 return;
486
487         screen().hideCursor();
488
489         Row * cursorrow = bv_->text->cursor.row();
490         bv_->text->setCursorFromCoordinates(bv_, x, y + bv_->text->first_y);
491 #if 0
492         // sorry for this but I have a strange error that the y value jumps at
493         // a certain point. This seems like an error in my xforms library or
494         // in some other local environment, but I would like to leave this here
495         // for the moment until I can remove this (Jug 20020418)
496         if (y_before < bv_->text->cursor.y())
497                 lyxerr << y_before << ":" << bv_->text->cursor.y() << endl;
498 #endif
499         // This is to allow jumping over large insets
500         if (cursorrow == bv_->text->cursor.row()) {
501                 if (y >= int(workarea().workHeight())) {
502                         bv_->text->cursorDown(bv_, false);
503                 } else if (y < 0) {
504                         bv_->text->cursorUp(bv_, false);
505                 }
506         }
507
508         if (!bv_->text->selection.set())
509                 update(bv_->text, BufferView::UPDATE); // Maybe an empty line was deleted
510
511         bv_->text->setSelection(bv_);
512         screen().toggleToggle(bv_->text, bv_);
513         fitCursor();
514         showCursor();
515 }
516
517
518 // Single-click on work area
519 void BufferView::Pimpl::workAreaButtonPress(int xpos, int ypos,
520                                             mouse_button::state button)
521 {
522         if (!buffer_)
523                 return;
524
525         // ok ok, this is a hack (for xforms)
526         if (button == mouse_button::button4) {
527                 scroll(-lyxrc.wheel_jump);
528                 // We shouldn't go further down as we really should only do the
529                 // scrolling and be done with this. Otherwise we may open some
530                 // dialogs (Jug 20020424).
531                 return;
532         } else if (button == mouse_button::button5) {
533                 scroll(lyxrc.wheel_jump);
534                 // We shouldn't go further down as we really should only do the
535                 // scrolling and be done with this. Otherwise we may open some
536                 // dialogs (Jug 20020424).
537                 return;
538         }
539
540         Inset * inset_hit = checkInsetHit(bv_->text, xpos, ypos);
541
542         // Middle button press pastes if we have a selection
543         // We do this here as if the selection was inside an inset
544         // it could get cleared on the unlocking of the inset so
545         // we have to check this first
546         bool paste_internally = false;
547         if (button == mouse_button::button2 && bv_->getLyXText()->selection.set()) {
548                 owner_->dispatch(FuncRequest(LFUN_COPY));
549                 paste_internally = true;
550         }
551
552         int const screen_first = bv_->text->first_y;
553
554         if (bv_->theLockingInset()) {
555                 // We are in inset locking mode
556
557                 // Check whether the inset was hit. If not reset mode,
558                 // otherwise give the event to the inset
559                 if (inset_hit == bv_->theLockingInset()) {
560                         FuncRequest cmd(bv_, LFUN_MOUSE_PRESS, xpos, ypos, button);
561                         bv_->theLockingInset()->localDispatch(cmd);
562                         return;
563                 }
564                 bv_->unlockInset(bv_->theLockingInset());
565         }
566
567         if (!inset_hit)
568                 selection_possible = true;
569         screen().hideCursor();
570
571         // Clear the selection
572         screen().toggleSelection(bv_->text, bv_);
573         bv_->text->clearSelection();
574         bv_->text->fullRebreak(bv_);
575         update();
576         updateScrollbar();
577
578         // Single left click in math inset?
579         if (isHighlyEditableInset(inset_hit)) {
580                 // Highly editable inset, like math
581                 UpdatableInset * inset = static_cast<UpdatableInset *>(inset_hit);
582                 selection_possible = false;
583                 owner_->updateLayoutChoice();
584                 owner_->message(inset->editMessage());
585                 //inset->edit(bv_, xpos, ypos, button);
586                 // We just have to lock the inset before calling a PressEvent on it!
587                 // we don't need the edit() call here! (Jug20020329)
588                 if (!bv_->lockInset(inset)) {
589                         lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
590                 }
591                 FuncRequest cmd(bv_, LFUN_MOUSE_PRESS, xpos, ypos, button);
592                 inset->localDispatch(cmd);
593                 return;
594         }
595         // I'm not sure we should continue here if we hit an inset (Jug20020403)
596
597         // Right click on a footnote flag opens float menu
598         if (button == mouse_button::button3) {
599                 selection_possible = false;
600                 return;
601         }
602
603         if (!inset_hit) // otherwise it was already set in checkInsetHit(...)
604                 bv_->text->setCursorFromCoordinates(bv_, xpos, ypos + screen_first);
605         finishUndo();
606         bv_->text->selection.cursor = bv_->text->cursor;
607         bv_->text->cursor.x_fix(bv_->text->cursor.x());
608
609         owner_->updateLayoutChoice();
610         if (fitCursor()) {
611                 selection_possible = false;
612         }
613
614         // Insert primary selection with middle mouse
615         // if there is a local selection in the current buffer,
616         // insert this
617         if (button == mouse_button::button2) {
618                 if (paste_internally)
619                         owner_->dispatch(FuncRequest(LFUN_PASTE));
620                 else
621                         owner_->dispatch(FuncRequest(LFUN_PASTESELECTION, "paragraph"));
622                 selection_possible = false;
623                 return;
624         }
625 }
626
627
628 void BufferView::Pimpl::doubleClick(int /*x*/, int /*y*/, mouse_button::state button)
629 {
630         if (!buffer_)
631                 return;
632
633         LyXText * text = bv_->getLyXText();
634
635         if (text->bv_owner && bv_->theLockingInset())
636                 return;
637
638         if (button == mouse_button::button1) {
639                 if (text->bv_owner) {
640                         screen().hideCursor();
641                         screen().toggleSelection(text, bv_);
642                         text->selectWord(bv_, LyXText::WHOLE_WORD_STRICT);
643                         screen().toggleSelection(text, bv_, false);
644                 } else {
645                         text->selectWord(bv_, LyXText::WHOLE_WORD_STRICT);
646                 }
647                 // This will fit the cursor on the screen if necessary
648                 update(text, BufferView::SELECT|BufferView::FITCUR);
649                 workarea().haveSelection(bv_->getLyXText()->selection.set());
650         }
651 }
652
653
654 void BufferView::Pimpl::tripleClick(int /*x*/, int /*y*/, mouse_button::state button)
655 {
656         if (!buffer_)
657                 return;
658
659         LyXText * text = bv_->getLyXText();
660
661         if (text->bv_owner && bv_->theLockingInset())
662             return;
663
664         if (button == mouse_button::button1) {
665                 if (text->bv_owner) {
666                         screen().hideCursor();
667                         screen().toggleSelection(text, bv_);
668                 }
669                 text->cursorHome(bv_);
670                 text->selection.cursor = text->cursor;
671                 text->cursorEnd(bv_);
672                 text->setSelection(bv_);
673                 if (text->bv_owner) {
674                         screen().toggleSelection(text, bv_, false);
675                 }
676                 // This will fit the cursor on the screen if necessary
677                 update(text, BufferView::SELECT|BufferView::FITCUR);
678                 workarea().haveSelection(bv_->getLyXText()->selection.set());
679         }
680 }
681
682
683 void BufferView::Pimpl::selectionRequested()
684 {
685         static string sel;
686
687         if (!available())
688                 return;
689
690         LyXText * text = bv_->getLyXText();
691
692         if (text->selection.set() &&
693                 (!bv_->text->xsel_cache.set() ||
694                  text->selection.start != bv_->text->xsel_cache.start ||
695                  text->selection.end != bv_->text->xsel_cache.end))
696         {
697                 bv_->text->xsel_cache = text->selection;
698                 sel = text->selectionAsString(bv_->buffer(), false);
699         } else if (!text->selection.set()) {
700                 sel = string();
701                 bv_->text->xsel_cache.set(false);
702         }
703         if (!sel.empty()) {
704                 workarea().putClipboard(sel);
705         }
706 }
707
708
709 void BufferView::Pimpl::selectionLost()
710 {
711         if (available()) {
712                 hideCursor();
713                 toggleSelection();
714                 bv_->getLyXText()->clearSelection();
715                 showCursor();
716                 bv_->text->xsel_cache.set(false);
717         }
718 }
719
720
721 void BufferView::Pimpl::workAreaButtonRelease(int x, int y,
722                                               mouse_button::state button)
723 {
724         // do nothing if we used the mouse wheel
725         if (!buffer_ || button == mouse_button::button4 || button == mouse_button::button5)
726                 return;
727
728         // If we hit an inset, we have the inset coordinates in these
729         // and inset_hit points to the inset.  If we do not hit an
730         // inset, inset_hit is 0, and inset_x == x, inset_y == y.
731         Inset * inset_hit = checkInsetHit(bv_->text, x, y);
732
733         if (bv_->theLockingInset()) {
734                 // We are in inset locking mode.
735
736                 // LyX does a kind of work-area grabbing for insets.
737                 // Only a ButtonPress FuncRequest outside the inset will
738                 // force a insetUnlock.
739                 FuncRequest cmd(bv_, LFUN_MOUSE_RELEASE, x, y, button);
740                 bv_->theLockingInset()->localDispatch(cmd);
741                 return;
742         }
743
744         selection_possible = false;
745
746         if (button == mouse_button::button2)
747                 return;
748
749         // finish selection
750         if (button == mouse_button::button1) {
751                 workarea().haveSelection(bv_->getLyXText()->selection.set());
752         }
753
754         switchKeyMap();
755         owner_->view_state_changed();
756         owner_->updateMenubar();
757         owner_->updateToolbar();
758
759         // Did we hit an editable inset?
760         if (inset_hit) {
761                 selection_possible = false;
762
763                 // if we reach this point with a selection, it
764                 // must mean we are currently selecting.
765                 // But we don't want to open the inset
766                 // because that is annoying for the user.
767                 // So just pretend we didn't hit it.
768                 // this is OK because a "kosher" ButtonRelease
769                 // will follow a ButtonPress that clears
770                 // the selection.
771                 // Note this also fixes selection drawing
772                 // problems if we end up opening an inset
773                 if (bv_->getLyXText()->selection.set())
774                         return;
775
776                 // CHECK fix this proper in 0.13
777                 // well, maybe 13.0 !!!!!!!!!
778
779                 // Following a ref shouldn't issue
780                 // a push on the undo-stack
781                 // anylonger, now that we have
782                 // keybindings for following
783                 // references and returning from
784                 // references.  IMHO though, it
785                 // should be the inset's own business
786                 // to push or not push on the undo
787                 // stack. They don't *have* to
788                 // alter the document...
789                 // (Joacim)
790                 // ...or maybe the SetCursorParUndo()
791                 // below isn't necessary at all anylonger?
792                 if (inset_hit->lyxCode() == Inset::REF_CODE) {
793                         setCursorParUndo(bv_);
794                 }
795
796                 owner_->message(inset_hit->editMessage());
797
798                 if (isHighlyEditableInset(inset_hit)) {
799                         // Highly editable inset, like math
800                         UpdatableInset *inset = (UpdatableInset *)inset_hit;
801                         FuncRequest cmd(bv_, LFUN_MOUSE_RELEASE, x, y, button);
802                         inset->localDispatch(cmd);
803                 } else {
804                         FuncRequest cmd(bv_, LFUN_MOUSE_RELEASE, x, y, button);
805                         inset_hit->localDispatch(cmd);
806                         // IMO this is a grosshack! Inset's should be changed so that
807                         // they call the actions they have to do with the insetButtonRel.
808                         // function and not in the edit(). This should be changed
809                         // (Jug 20020329)
810 #ifdef WITH_WARNINGS
811 #warning Please remove donot call inset->edit() here (Jug 20020812)
812 #endif
813                         inset_hit->edit(bv_, x, y, button);
814                 }
815                 return;
816         }
817
818         // Maybe we want to edit a bibitem ale970302
819         if (bv_->text->cursor.par()->bibkey) {
820                 bool const is_rtl = bv_->text->cursor.par()->isRightToLeftPar(buffer_->params);
821                 int const width = bibitemMaxWidth(bv_, buffer_->params.getLyXTextClass().defaultfont());
822                 if ((is_rtl && x > bv_->text->workWidth(bv_)-20-width) ||
823                     (!is_rtl && x < 20+width)) {
824                         bv_->text->cursor.par()->bibkey->edit(bv_, 0, 0, mouse_button::none);
825                 }
826         }
827
828         return;
829 }
830
831
832 Box BufferView::Pimpl::insetDimensions(LyXText const & text,
833                                        LyXCursor const & cursor) const
834 {
835         Paragraph /*const*/ & par = *cursor.par();
836         pos_type const pos = cursor.pos();
837
838         lyx::Assert(par.getInset(pos));
839
840         Inset const & inset(*par.getInset(pos));
841
842         LyXFont const & font = text.getFont(buffer_, &par, pos);
843
844         int const width = inset.width(bv_, font);
845         int const inset_x = font.isVisibleRightToLeft()
846                 ? (cursor.ix() - width) : cursor.ix();
847
848         return Box(
849                 inset_x + inset.scroll(),
850                 inset_x + width,
851                 cursor.iy() - inset.ascent(bv_, font),
852                 cursor.iy() + inset.descent(bv_, font));
853 }
854
855
856 Inset * BufferView::Pimpl::checkInset(LyXText const & text,
857                                       LyXCursor const & cursor,
858                                       int & x, int & y) const
859 {
860         pos_type const pos(cursor.pos());
861         Paragraph /*const*/ & par(*cursor.par());
862
863         if (pos >= par.size() || !par.isInset(pos)) {
864                 return 0;
865         }
866
867         Inset /*const*/ * inset = par.getInset(pos);
868
869         if (!isEditableInset(inset)) {
870                 return 0;
871         }
872
873         Box b(insetDimensions(text, cursor));
874
875         if (!b.contained(x, y)) {
876                 lyxerr[Debug::GUI] << "Missed inset at x,y " << x << "," << y
877                         << " box " << b << endl;
878                 return 0;
879         }
880
881         text.setCursor(bv_, &par, pos, true);
882
883         x -= b.x1;
884         // The origin of an inset is on the baseline
885         y -= text.cursor.iy();
886
887         return inset;
888 }
889
890
891 Inset * BufferView::Pimpl::checkInsetHit(LyXText * text, int & x, int & y)
892 {
893         int y_tmp = y + text->first_y;
894
895         LyXCursor cursor;
896         text->setCursorFromCoordinates(bv_, cursor, x, y_tmp);
897
898         Inset * inset(checkInset(*text, cursor, x, y_tmp));
899
900         if (inset) {
901                 y = y_tmp;
902                 return inset;
903         }
904
905         // look at previous position
906
907         if (cursor.pos() == 0) {
908                 return 0;
909         }
910
911         // move back one
912         text->setCursor(bv_, cursor, cursor.par(), cursor.pos() - 1, true);
913
914         inset = checkInset(*text, cursor, x, y_tmp);
915         if (inset) {
916                 y = y_tmp;
917         }
918         return inset;
919 }
920
921
922 void BufferView::Pimpl::workAreaResize()
923 {
924         static int work_area_width;
925         static int work_area_height;
926
927         bool const widthChange = workarea().workWidth() != work_area_width;
928         bool const heightChange = workarea().workHeight() != work_area_height;
929
930         // update from work area
931         work_area_width = workarea().workWidth();
932         work_area_height = workarea().workHeight();
933
934         if (buffer_ != 0) {
935                 if (widthChange) {
936                         // The visible LyXView need a resize
937                         resizeCurrentBuffer();
938
939                         // Remove all texts from the textcache
940                         // This is not _really_ what we want to do. What
941                         // we really want to do is to delete in textcache
942                         // that does not have a BufferView with matching
943                         // width, but as long as we have only one BufferView
944                         // deleting all gives the same result.
945                         if (lyxerr.debugging())
946                                 textcache.show(lyxerr, "Expose delete all");
947                         textcache.clear();
948                         // FIXME: this is aalready done in resizeCurrentBuffer() ??
949                         buffer_->resizeInsets(bv_);
950                 } else if (heightChange) {
951                         // fitCursor() ensures we don't jump back
952                         // to the start of the document on vertical
953                         // resize
954                         fitCursor();
955                 }
956         }
957
958         if (widthChange || heightChange) {
959                 repaint();
960         }
961
962         // always make sure that the scrollbar is sane.
963         updateScrollbar();
964         owner_->updateLayoutChoice();
965         return;
966 }
967
968
969 void BufferView::Pimpl::update()
970 {
971         if (!bv_->theLockingInset() || !bv_->theLockingInset()->nodraw()) {
972                 LyXText::text_status st = bv_->text->status();
973                 screen().update(bv_->text, bv_);
974                 bool fitc = false;
975                 while (bv_->text->status() == LyXText::CHANGED_IN_DRAW) {
976                         bv_->text->fullRebreak(bv_);
977                         st = LyXText::NEED_MORE_REFRESH;
978                         bv_->text->setCursor(bv_, bv_->text->cursor.par(),
979                                              bv_->text->cursor.pos());
980                         if (bv_->text->selection.set()) {
981                                 bv_->text->setCursor(bv_, bv_->text->selection.start,
982                                                      bv_->text->selection.start.par(),
983                                                      bv_->text->selection.start.pos());
984                                 bv_->text->setCursor(bv_, bv_->text->selection.end,
985                                                      bv_->text->selection.end.par(),
986                                                      bv_->text->selection.end.pos());
987                         }
988                         fitc = true;
989                         bv_->text->status(bv_, st);
990                         screen().update(bv_->text, bv_);
991                 }
992                 // do this here instead of in the screen::update because of
993                 // the above loop!
994                 bv_->text->status(bv_, LyXText::UNCHANGED);
995                 if (fitc)
996                         fitCursor();
997         }
998 }
999
1000 // Values used when calling update:
1001 // -3 - update
1002 // -2 - update, move sel_cursor if selection, fitcursor
1003 // -1 - update, move sel_cursor if selection, fitcursor, mark dirty
1004 //  0 - update, move sel_cursor if selection, fitcursor
1005 //  1 - update, move sel_cursor if selection, fitcursor, mark dirty
1006 //  3 - update, move sel_cursor if selection
1007 //
1008 // update -
1009 // a simple redraw of the parts that need refresh
1010 //
1011 // move sel_cursor if selection -
1012 // the text's sel_cursor is moved if there is selection is progress
1013 //
1014 // fitcursor -
1015 // fitCursor() is called and the scrollbar updated
1016 //
1017 // mark dirty -
1018 // the buffer is marked dirty.
1019 //
1020 // enum {
1021 //       UPDATE = 0,
1022 //       SELECT = 1,
1023 //       FITCUR = 2,
1024 //       CHANGE = 4
1025 // };
1026 //
1027 // UPDATE_ONLY = UPDATE;
1028 // UPDATE_SELECT = UPDATE | SELECT;
1029 // UPDATE_SELECT_MOVE = UPDATE | SELECT | FITCUR;
1030 // UPDATE_SELECT_MOVE_AFTER_CHANGE = UPDATE | SELECT | FITCUR | CHANGE;
1031 //
1032 // update(-3) -> update(0)         -> update(0) -> update(UPDATE)
1033 // update(-2) -> update(1 + 2)     -> update(3) -> update(SELECT|FITCUR)
1034 // update(-1) -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
1035 // update(1)  -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
1036 // update(3)  -> update(1)         -> update(1) -> update(SELECT)
1037
1038 void BufferView::Pimpl::update(LyXText * text, BufferView::UpdateCodes f)
1039 {
1040         owner_->updateLayoutChoice();
1041
1042         if (!text->selection.set() && (f & SELECT)) {
1043                 text->selection.cursor = text->cursor;
1044         }
1045
1046         text->fullRebreak(bv_);
1047
1048         if (text->inset_owner) {
1049                 text->inset_owner->setUpdateStatus(bv_, InsetText::NONE);
1050                 updateInset(text->inset_owner, false);
1051         } else {
1052                 update();
1053         }
1054
1055         if ((f & FITCUR)) {
1056                 fitCursor();
1057         }
1058
1059         if ((f & CHANGE)) {
1060                 buffer_->markDirty();
1061         }
1062 }
1063
1064
1065 // Callback for cursor timer
1066 void BufferView::Pimpl::cursorToggle()
1067 {
1068         if (!buffer_) {
1069                 cursor_timeout.restart();
1070                 return;
1071         }
1072
1073         /* FIXME */
1074         extern void reapSpellchecker(void);
1075         reapSpellchecker();
1076
1077         if (!bv_->theLockingInset()) {
1078                 screen().cursorToggle(bv_);
1079         } else {
1080                 bv_->theLockingInset()->toggleInsetCursor(bv_);
1081         }
1082
1083         cursor_timeout.restart();
1084 }
1085
1086
1087 bool BufferView::Pimpl::available() const
1088 {
1089         if (buffer_ && bv_->text)
1090                 return true;
1091         return false;
1092 }
1093
1094
1095 void BufferView::Pimpl::beforeChange(LyXText * text)
1096 {
1097         toggleSelection();
1098         text->clearSelection();
1099 }
1100
1101
1102 void BufferView::Pimpl::finishChange(bool fitcur)
1103 {
1104         finishUndo();
1105         moveCursorUpdate(fitcur);
1106         bv_->owner()->view_state_changed();
1107 }
1108
1109
1110 void BufferView::Pimpl::savePosition(unsigned int i)
1111 {
1112         if (i >= saved_positions_num)
1113                 return;
1114         saved_positions[i] = Position(buffer_->fileName(),
1115                                       bv_->text->cursor.par()->id(),
1116                                       bv_->text->cursor.pos());
1117         if (i > 0) {
1118                 ostringstream str;
1119                 str << _("Saved bookmark") << ' ' << i;
1120                 owner_->message(str.str().c_str());
1121         }
1122 }
1123
1124
1125 void BufferView::Pimpl::restorePosition(unsigned int i)
1126 {
1127         if (i >= saved_positions_num)
1128                 return;
1129
1130         string const fname = saved_positions[i].filename;
1131
1132         beforeChange(bv_->text);
1133
1134         if (fname != buffer_->fileName()) {
1135                 Buffer * b = bufferlist.exists(fname) ?
1136                         bufferlist.getBuffer(fname) :
1137                         bufferlist.loadLyXFile(fname); // don't ask, just load it
1138                 if (b != 0) buffer(b);
1139         }
1140
1141         Paragraph * par = buffer_->getParFromID(saved_positions[i].par_id);
1142         if (!par)
1143                 return;
1144
1145         bv_->text->setCursor(bv_, par,
1146                              min(par->size(), saved_positions[i].par_pos));
1147
1148         update(bv_->text, BufferView::SELECT | BufferView::FITCUR);
1149         if (i > 0) {
1150                 ostringstream str;
1151                 str << _("Moved to bookmark") << ' ' << i;
1152                 owner_->message(str.str().c_str());
1153         }
1154 }
1155
1156
1157 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
1158 {
1159         if (i >= saved_positions_num)
1160                 return false;
1161
1162         return !saved_positions[i].filename.empty();
1163 }
1164
1165
1166 void BufferView::Pimpl::switchKeyMap()
1167 {
1168         if (!lyxrc.rtl_support)
1169                 return;
1170
1171         LyXText * text = bv_->getLyXText();
1172         if (text->real_current_font.isRightToLeft()
1173             && !(bv_->theLockingInset()
1174                  && bv_->theLockingInset()->lyxCode() == Inset::ERT_CODE))
1175         {
1176                 if (owner_->getIntl().keymap == Intl::PRIMARY)
1177                         owner_->getIntl().KeyMapSec();
1178         } else {
1179                 if (owner_->getIntl().keymap == Intl::SECONDARY)
1180                         owner_->getIntl().KeyMapPrim();
1181         }
1182 }
1183
1184
1185 void BufferView::Pimpl::insetUnlock()
1186 {
1187         if (bv_->theLockingInset()) {
1188                 bv_->theLockingInset()->insetUnlock(bv_);
1189                 bv_->theLockingInset(0);
1190                 finishUndo();
1191         }
1192 }
1193
1194
1195 void BufferView::Pimpl::showCursor()
1196 {
1197         if (bv_->theLockingInset())
1198                 bv_->theLockingInset()->showInsetCursor(bv_);
1199         else
1200                 screen().showCursor(bv_->text, bv_);
1201 }
1202
1203
1204 void BufferView::Pimpl::hideCursor()
1205 {
1206         if (!bv_->theLockingInset())
1207                 screen().hideCursor();
1208 }
1209
1210
1211 void BufferView::Pimpl::toggleSelection(bool b)
1212 {
1213         if (bv_->theLockingInset())
1214                 bv_->theLockingInset()->toggleSelection(bv_, b);
1215         screen().toggleSelection(bv_->text, bv_, b);
1216 }
1217
1218
1219 void BufferView::Pimpl::toggleToggle()
1220 {
1221         screen().toggleToggle(bv_->text, bv_);
1222 }
1223
1224
1225 void BufferView::Pimpl::center()
1226 {
1227         LyXText * t = bv_->text;
1228
1229         beforeChange(t);
1230         int const half_height = workarea().workHeight() / 2;
1231         int new_y = 0;
1232
1233         if (t->cursor.y() > half_height) {
1234                 new_y = t->cursor.y() - half_height;
1235         }
1236
1237         // FIXME: can we do this w/o calling screen directly ?
1238         // This updates first_y but means the fitCursor() call
1239         // from the update(FITCUR) doesn't realise that we might
1240         // have moved (e.g. from GOTOPARAGRAPH), so doesn't cause
1241         // the scrollbar to be updated as it should, so we have
1242         // to do it manually. Any operation that does a center()
1243         // and also might have moved first_y must make sure to call
1244         // updateScrollbar() currently. Never mind that this is a
1245         // pretty obfuscated way of updating t->first_y
1246         screen().draw(t, bv_, new_y);
1247
1248         update(t, BufferView::SELECT | BufferView::FITCUR);
1249 }
1250
1251
1252 void BufferView::Pimpl::stuffClipboard(string const & stuff) const
1253 {
1254         workarea().putClipboard(stuff);
1255 }
1256
1257
1258 /*
1259  * Dispatch functions for actions which can be valid for BufferView->text
1260  * and/or InsetText->text!!!
1261  */
1262
1263
1264 void BufferView::Pimpl::moveCursorUpdate(bool selecting, bool fitcur)
1265 {
1266         LyXText * lt = bv_->getLyXText();
1267
1268         if (selecting || lt->selection.mark()) {
1269                 lt->setSelection(bv_);
1270                 if (lt->bv_owner)
1271                         toggleToggle();
1272                 else
1273                         updateInset(lt->inset_owner, false);
1274         }
1275         if (lt->bv_owner) {
1276                 if (fitcur)
1277                         update(lt, BufferView::SELECT|BufferView::FITCUR);
1278                 else
1279                         update(lt, BufferView::SELECT);
1280                 showCursor();
1281         } else if (bv_->text->status() != LyXText::UNCHANGED) {
1282                 bv_->theLockingInset()->hideInsetCursor(bv_);
1283                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
1284                 showCursor();
1285         }
1286
1287         if (!lt->selection.set())
1288                 workarea().haveSelection(false);
1289
1290         switchKeyMap();
1291 }
1292
1293
1294 Inset * BufferView::Pimpl::getInsetByCode(Inset::Code code)
1295 {
1296 #if 0
1297         LyXCursor cursor = bv_->getLyXText()->cursor;
1298         Buffer::inset_iterator it =
1299                 find_if(Buffer::inset_iterator(
1300                         cursor.par(), cursor.pos()),
1301                         buffer_->inset_iterator_end(),
1302                         lyx::compare_memfun(&Inset::lyxCode, code));
1303         return it != buffer_->inset_iterator_end() ? (*it) : 0;
1304 #else
1305         // Ok, this is a little bit too brute force but it
1306         // should work for now. Better infrastructure is comming. (Lgb)
1307
1308         Buffer * b = bv_->buffer();
1309         LyXCursor cursor = bv_->getLyXText()->cursor;
1310
1311         Buffer::inset_iterator beg = b->inset_iterator_begin();
1312         Buffer::inset_iterator end = b->inset_iterator_end();
1313
1314         bool cursor_par_seen = false;
1315
1316         for (; beg != end; ++beg) {
1317                 if (beg.getPar() == cursor.par()) {
1318                         cursor_par_seen = true;
1319                 }
1320                 if (cursor_par_seen) {
1321                         if (beg.getPar() == cursor.par()
1322                             && beg.getPos() >= cursor.pos()) {
1323                                 break;
1324                         } else if (beg.getPar() != cursor.par()) {
1325                                 break;
1326                         }
1327                 }
1328
1329         }
1330         if (beg != end) {
1331                 // Now find the first inset that matches code.
1332                 for (; beg != end; ++beg) {
1333                         if (beg->lyxCode() == code) {
1334                                 return &(*beg);
1335                         }
1336                 }
1337         }
1338         return 0;
1339 #endif
1340 }
1341
1342
1343 void BufferView::Pimpl::MenuInsertLyXFile(string const & filen)
1344 {
1345         string filename = filen;
1346
1347         if (filename.empty()) {
1348                 // Launch a file browser
1349                 string initpath = lyxrc.document_path;
1350
1351                 if (available()) {
1352                         string const trypath = owner_->buffer()->filePath();
1353                         // If directory is writeable, use this as default.
1354                         if (IsDirWriteable(trypath))
1355                                 initpath = trypath;
1356                 }
1357
1358                 FileDialog fileDlg(bv_->owner(),
1359                                    _("Select LyX document to insert"),
1360                         LFUN_FILE_INSERT,
1361                         make_pair(string(_("Documents|#o#O")),
1362                                   string(lyxrc.document_path)),
1363                         make_pair(string(_("Examples|#E#e")),
1364                                   string(AddPath(system_lyxdir, "examples"))));
1365
1366                 FileDialog::Result result =
1367                         fileDlg.Select(initpath,
1368                                        _("*.lyx| LyX Documents (*.lyx)"));
1369
1370                 if (result.first == FileDialog::Later)
1371                         return;
1372
1373                 filename = result.second;
1374
1375                 // check selected filename
1376                 if (filename.empty()) {
1377                         owner_->message(_("Canceled."));
1378                         return;
1379                 }
1380         }
1381
1382         // get absolute path of file and add ".lyx" to the filename if
1383         // necessary
1384         filename = FileSearch(string(), filename, "lyx");
1385
1386         string const disp_fn(MakeDisplayPath(filename));
1387
1388         ostringstream s1;
1389         s1 << _("Inserting document") << ' '
1390            << disp_fn << " ...";
1391         owner_->message(s1.str().c_str());
1392         bool const res = bv_->insertLyXFile(filename);
1393         if (res) {
1394                 ostringstream str;
1395                 str << _("Document") << ' ' << disp_fn
1396                     << ' ' << _("inserted.");
1397                 owner_->message(str.str().c_str());
1398         } else {
1399                 ostringstream str;
1400                 str << _("Could not insert document") << ' '
1401                     << disp_fn;
1402                 owner_->message(str.str().c_str());
1403         }
1404 }
1405
1406
1407 bool BufferView::Pimpl::dispatch(FuncRequest const & ev)
1408 {
1409         lyxerr[Debug::ACTION] << "BufferView::Pimpl::Dispatch: action["
1410           << ev.action <<"] arg[" << ev.argument << "]" << endl;
1411
1412         LyXTextClass const & tclass = buffer_->params.getLyXTextClass();
1413
1414         switch (ev.action) {
1415
1416         case LFUN_TOC_INSERT:
1417         {
1418                 InsetCommandParams p;
1419                 p.setCmdName("tableofcontents");
1420                 Inset * inset = new InsetTOC(p);
1421                 if (!insertInset(inset, tclass.defaultLayoutName()))
1422                         delete inset;
1423                 break;
1424         }
1425
1426         case LFUN_SCROLL_INSET:
1427                 // this is not handled here as this function is only active
1428                 // if we have a locking_inset and that one is (or contains)
1429                 // a tabular-inset
1430                 break;
1431
1432         case LFUN_INSET_GRAPHICS:
1433         {
1434                 Inset * new_inset = new InsetGraphics;
1435                 if (!insertInset(new_inset)) {
1436                         delete new_inset;
1437                 } else {
1438                         // this is need because you don't use a inset->Edit()
1439                         updateInset(new_inset, true);
1440                         new_inset->edit(bv_);
1441                 }
1442                 break;
1443         }
1444
1445         case LFUN_PASTE:
1446                 bv_->paste();
1447                 switchKeyMap();
1448                 break;
1449
1450         case LFUN_CUT:
1451                 bv_->cut();
1452                 break;
1453
1454         case LFUN_COPY:
1455                 bv_->copy();
1456                 break;
1457
1458         case LFUN_LAYOUT_COPY:
1459                 bv_->copyEnvironment();
1460                 break;
1461
1462         case LFUN_LAYOUT_PASTE:
1463                 bv_->pasteEnvironment();
1464                 switchKeyMap();
1465                 break;
1466
1467         case LFUN_GOTOERROR:
1468                 gotoInset(Inset::ERROR_CODE, false);
1469                 break;
1470
1471         case LFUN_GOTONOTE:
1472                 gotoInset(Inset::NOTE_CODE, false);
1473                 break;
1474
1475         case LFUN_REFERENCE_GOTO:
1476         {
1477                 vector<Inset::Code> tmp;
1478                 tmp.push_back(Inset::LABEL_CODE);
1479                 tmp.push_back(Inset::REF_CODE);
1480                 gotoInset(tmp, true);
1481                 break;
1482         }
1483
1484         case LFUN_DEPTH_MIN:
1485                 changeDepth(bv_, bv_->getLyXText(), -1);
1486                 break;
1487
1488         case LFUN_DEPTH_PLUS:
1489                 changeDepth(bv_, bv_->getLyXText(), 1);
1490                 break;
1491
1492         case LFUN_FREE:
1493                 owner_->getDialogs().setUserFreeFont();
1494                 break;
1495
1496         case LFUN_FILE_INSERT:
1497                 MenuInsertLyXFile(ev.argument);
1498                 break;
1499
1500         case LFUN_FILE_INSERT_ASCII_PARA:
1501                 InsertAsciiFile(bv_, ev.argument, true);
1502                 break;
1503
1504         case LFUN_FILE_INSERT_ASCII:
1505                 InsertAsciiFile(bv_, ev.argument, false);
1506                 break;
1507
1508         case LFUN_LANGUAGE:
1509                 lang(bv_, ev.argument);
1510                 switchKeyMap();
1511                 owner_->view_state_changed();
1512                 break;
1513
1514         case LFUN_EMPH:
1515                 emph(bv_);
1516                 owner_->view_state_changed();
1517                 break;
1518
1519         case LFUN_BOLD:
1520                 bold(bv_);
1521                 owner_->view_state_changed();
1522                 break;
1523
1524         case LFUN_NOUN:
1525                 noun(bv_);
1526                 owner_->view_state_changed();
1527                 break;
1528
1529         case LFUN_CODE:
1530                 code(bv_);
1531                 owner_->view_state_changed();
1532                 break;
1533
1534         case LFUN_SANS:
1535                 sans(bv_);
1536                 owner_->view_state_changed();
1537                 break;
1538
1539         case LFUN_ROMAN:
1540                 roman(bv_);
1541                 owner_->view_state_changed();
1542                 break;
1543
1544         case LFUN_DEFAULT:
1545                 styleReset(bv_);
1546                 owner_->view_state_changed();
1547                 break;
1548
1549         case LFUN_UNDERLINE:
1550                 underline(bv_);
1551                 owner_->view_state_changed();
1552                 break;
1553
1554         case LFUN_FONT_SIZE:
1555                 fontSize(bv_, ev.argument);
1556                 owner_->view_state_changed();
1557                 break;
1558
1559         case LFUN_FONT_STATE:
1560                 owner_->getLyXFunc().setMessage(currentState(bv_));
1561                 break;
1562
1563         case LFUN_INSERT_LABEL:
1564                 MenuInsertLabel(bv_, ev.argument);
1565                 break;
1566
1567         case LFUN_REF_INSERT:
1568                 if (ev.argument.empty()) {
1569                         InsetCommandParams p("ref");
1570                         owner_->getDialogs().createRef(p.getAsString());
1571                 } else {
1572                         InsetCommandParams p;
1573                         p.setFromString(ev.argument);
1574
1575                         InsetRef * inset = new InsetRef(p, *buffer_);
1576                         if (!insertInset(inset))
1577                                 delete inset;
1578                         else
1579                                 updateInset(inset, true);
1580                 }
1581                 break;
1582
1583         case LFUN_BOOKMARK_SAVE:
1584                 savePosition(strToUnsignedInt(ev.argument));
1585                 break;
1586
1587         case LFUN_BOOKMARK_GOTO:
1588                 restorePosition(strToUnsignedInt(ev.argument));
1589                 break;
1590
1591         case LFUN_REF_GOTO:
1592         {
1593                 string label = ev.argument;
1594                 if (label.empty()) {
1595                         InsetRef * inset =
1596                                 static_cast<InsetRef*>(getInsetByCode(Inset::REF_CODE));
1597                         if (inset) {
1598                                 label = inset->getContents();
1599                                 savePosition(0);
1600                         }
1601                 }
1602
1603                 if (!label.empty()) {
1604                         //bv_->savePosition(0);
1605                         if (!bv_->gotoLabel(label))
1606                                 Alert::alert(_("Error"),
1607                                            _("Couldn't find this label"),
1608                                            _("in current document."));
1609                 }
1610         }
1611         break;
1612
1613         case LFUN_QUOTE:
1614                 smartQuote();
1615                 break;
1616
1617         case LFUN_HTMLURL:
1618         case LFUN_URL:
1619         {
1620                 InsetCommandParams p;
1621                 if (ev.action == LFUN_HTMLURL)
1622                         p.setCmdName("htmlurl");
1623                 else
1624                         p.setCmdName("url");
1625                 owner_->getDialogs().createUrl(p.getAsString());
1626         }
1627         break;
1628
1629         case LFUN_INSERT_URL:
1630         {
1631                 InsetCommandParams p;
1632                 p.setFromString(ev.argument);
1633
1634                 InsetUrl * inset = new InsetUrl(p);
1635                 if (!insertInset(inset))
1636                         delete inset;
1637                 else
1638                         updateInset(inset, true);
1639         }
1640         break;
1641
1642         case LFUN_INSET_ERT:
1643                 insertAndEditInset(new InsetERT(buffer_->params));
1644                 break;
1645
1646         case LFUN_INSET_EXTERNAL:
1647                 insertAndEditInset(new InsetExternal);
1648                 break;
1649
1650         case LFUN_INSET_FOOTNOTE:
1651                 insertAndEditInset(new InsetFoot(buffer_->params));
1652                 break;
1653
1654         case LFUN_INSET_MARGINAL:
1655                 insertAndEditInset(new InsetMarginal(buffer_->params));
1656                 break;
1657
1658         case LFUN_INSET_MINIPAGE:
1659                 insertAndEditInset(new InsetMinipage(buffer_->params));
1660                 break;
1661
1662         case LFUN_INSERT_NOTE:
1663                 insertAndEditInset(new InsetNote(buffer_->params));
1664                 break;
1665
1666         case LFUN_INSET_OPTARG:
1667                 insertAndEditInset(new InsetOptArg(buffer_->params));
1668                 break;
1669
1670         case LFUN_INSET_FLOAT:
1671                 // check if the float type exist
1672                 if (floatList.typeExist(ev.argument)) {
1673                         insertAndEditInset(new InsetFloat(buffer_->params,
1674                                                           ev.argument));
1675                 } else {
1676                         lyxerr << "Non-existent float type: "
1677                                << ev.argument << endl;
1678                 }
1679                 break;
1680
1681         case LFUN_INSET_WIDE_FLOAT:
1682                 // check if the float type exist
1683                 if (floatList.typeExist(ev.argument)) {
1684                         InsetFloat * new_inset =
1685                                 new InsetFloat(buffer_->params, ev.argument);
1686                         new_inset->wide(true);
1687                         insertAndEditInset(new_inset);
1688                 } else {
1689                         lyxerr << "Non-existent float type: "
1690                                << ev.argument << endl;
1691                 }
1692                 break;
1693
1694 #if 0
1695         case LFUN_INSET_LIST:
1696                 insertAndEditInset(new InsetList);
1697                 break;
1698
1699         case LFUN_INSET_THEOREM:
1700                 insertAndEditInset(new InsetTheorem);
1701                 break;
1702 #endif
1703
1704         case LFUN_INSET_CAPTION:
1705         {
1706                 // Do we have a locking inset...
1707                 if (bv_->theLockingInset()) {
1708                         lyxerr << "Locking inset code: "
1709                                << static_cast<int>(bv_->theLockingInset()->lyxCode());
1710                         InsetCaption * new_inset =
1711                                 new InsetCaption(buffer_->params);
1712                         new_inset->setOwner(bv_->theLockingInset());
1713                         new_inset->setAutoBreakRows(true);
1714                         new_inset->setDrawFrame(0, InsetText::LOCKED);
1715                         new_inset->setFrameColor(0, LColor::captionframe);
1716                         if (insertInset(new_inset))
1717                                 new_inset->edit(bv_);
1718                         else
1719                                 delete new_inset;
1720                 }
1721         }
1722         break;
1723
1724         case LFUN_TABULAR_INSERT:
1725         {
1726                 if (ev.argument.empty()) {
1727                         owner_->getDialogs().showTabularCreate();
1728                         break;
1729                 }
1730
1731                 int r = 2;
1732                 int c = 2;
1733                 ::sscanf(ev.argument.c_str(),"%d%d", &r, &c);
1734                 InsetTabular * new_inset =
1735                         new InsetTabular(*buffer_, r, c);
1736                 bool const rtl =
1737                         bv_->getLyXText()->real_current_font.isRightToLeft();
1738                 if (!open_new_inset(new_inset, rtl))
1739                         delete new_inset;
1740         }
1741         break;
1742
1743
1744         // --- accented characters ---------------------------
1745
1746         case LFUN_UMLAUT:
1747         case LFUN_CIRCUMFLEX:
1748         case LFUN_GRAVE:
1749         case LFUN_ACUTE:
1750         case LFUN_TILDE:
1751         case LFUN_CEDILLA:
1752         case LFUN_MACRON:
1753         case LFUN_DOT:
1754         case LFUN_UNDERDOT:
1755         case LFUN_UNDERBAR:
1756         case LFUN_CARON:
1757         case LFUN_SPECIAL_CARON:
1758         case LFUN_BREVE:
1759         case LFUN_TIE:
1760         case LFUN_HUNG_UMLAUT:
1761         case LFUN_CIRCLE:
1762         case LFUN_OGONEK:
1763                 if (ev.argument.empty()) {
1764                         // As always...
1765                         owner_->getLyXFunc().handleKeyFunc(ev.action);
1766                 } else {
1767                         owner_->getLyXFunc().handleKeyFunc(ev.action);
1768                         owner_->getIntl().getTransManager()
1769                                 .TranslateAndInsert(ev.argument[0], bv_->getLyXText());
1770                         update(bv_->getLyXText(),
1771                                BufferView::SELECT
1772                                | BufferView::FITCUR
1773                                | BufferView::CHANGE);
1774                 }
1775                 break;
1776
1777         case LFUN_MATH_MACRO:
1778         case LFUN_MATH_DELIM:
1779         case LFUN_INSERT_MATRIX:
1780         case LFUN_INSERT_MATH:
1781         case LFUN_MATH_IMPORT_SELECTION: // Imports LaTeX from the X selection
1782         case LFUN_MATH_DISPLAY:          // Open or create a displayed math inset
1783         case LFUN_MATH_MODE:             // Open or create an inlined math inset
1784         case LFUN_GREEK:                 // Insert a single greek letter
1785                 mathDispatch(FuncRequest(bv_, ev.action, ev.argument));
1786                 break;
1787
1788         case LFUN_CITATION_INSERT:
1789         {
1790                 InsetCommandParams p;
1791                 p.setFromString(ev.argument);
1792
1793                 InsetCitation * inset = new InsetCitation(p);
1794                 if (!insertInset(inset))
1795                         delete inset;
1796                 else
1797                         updateInset(inset, true);
1798         }
1799         break;
1800
1801         case LFUN_INSERT_BIBTEX:
1802         {
1803                 // ale970405+lasgoutt970425
1804                 // The argument can be up to two tokens separated
1805                 // by a space. The first one is the bibstyle.
1806                 string const db = token(ev.argument, ' ', 0);
1807                 string bibstyle = token(ev.argument, ' ', 1);
1808                 if (bibstyle.empty())
1809                         bibstyle = "plain";
1810
1811                 InsetCommandParams p("BibTeX", db, bibstyle);
1812                 InsetBibtex * inset = new InsetBibtex(p);
1813
1814                 if (insertInset(inset)) {
1815                         if (ev.argument.empty())
1816                                 inset->edit(bv_);
1817                 } else
1818                         delete inset;
1819         }
1820         break;
1821
1822         // BibTeX data bases
1823         case LFUN_BIBDB_ADD:
1824         {
1825                 InsetBibtex * inset =
1826                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
1827                 if (inset) {
1828                         inset->addDatabase(ev.argument);
1829                 }
1830         }
1831         break;
1832
1833         case LFUN_BIBDB_DEL:
1834         {
1835                 InsetBibtex * inset =
1836                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
1837                 if (inset) {
1838                         inset->delDatabase(ev.argument);
1839                 }
1840         }
1841         break;
1842
1843         case LFUN_BIBTEX_STYLE:
1844         {
1845                 InsetBibtex * inset =
1846                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
1847                 if (inset) {
1848                         inset->setOptions(ev.argument);
1849                 }
1850         }
1851         break;
1852
1853         case LFUN_INDEX_INSERT:
1854         {
1855                 string entry = ev.argument;
1856                 if (entry.empty())
1857                         entry = bv_->getLyXText()->getStringToIndex(bv_);
1858
1859                 if (entry.empty()) {
1860                         owner_->getDialogs().createIndex();
1861                         break;
1862                 }
1863
1864                 InsetIndex * inset = new InsetIndex(InsetCommandParams("index", entry));
1865
1866                 if (!insertInset(inset)) {
1867                         delete inset;
1868                 } else {
1869                         updateInset(inset, true);
1870                 }
1871         }
1872         break;
1873
1874         case LFUN_INDEX_PRINT:
1875         {
1876                 InsetCommandParams p("printindex");
1877                 Inset * inset = new InsetPrintIndex(p);
1878                 if (!insertInset(inset, tclass.defaultLayoutName()))
1879                         delete inset;
1880         }
1881         break;
1882
1883         case LFUN_PARENTINSERT:
1884         {
1885                 InsetCommandParams p("lyxparent", ev.argument);
1886                 Inset * inset = new InsetParent(p, *buffer_);
1887                 if (!insertInset(inset, tclass.defaultLayoutName()))
1888                         delete inset;
1889         }
1890
1891         break;
1892
1893         case LFUN_CHILD_INSERT:
1894         {
1895                 InsetInclude::Params p;
1896                 p.cparams.setFromString(ev.argument);
1897                 p.masterFilename_ = buffer_->fileName();
1898
1899                 InsetInclude * inset = new InsetInclude(p);
1900                 if (!insertInset(inset))
1901                         delete inset;
1902                 else {
1903                         updateInset(inset, true);
1904                         bv_->owner()->getDialogs().showInclude(inset);
1905                 }
1906         }
1907         break;
1908
1909         case LFUN_FLOAT_LIST:
1910                 if (floatList.typeExist(ev.argument)) {
1911                         Inset * inset = new InsetFloatList(ev.argument);
1912                         if (!insertInset(inset, tclass.defaultLayoutName()))
1913                                 delete inset;
1914                 } else {
1915                         lyxerr << "Non-existent float type: "
1916                                << ev.argument << endl;
1917                 }
1918                 break;
1919
1920         case LFUN_THESAURUS_ENTRY:
1921         {
1922                 string arg = ev.argument;
1923
1924                 if (arg.empty()) {
1925                         arg = bv_->getLyXText()->selectionAsString(buffer_,
1926                                                                    false);
1927
1928                         // FIXME
1929                         if (arg.size() > 100 || arg.empty()) {
1930                                 // Get word or selection
1931                                 bv_->getLyXText()->selectWordWhenUnderCursor(bv_, LyXText::WHOLE_WORD);
1932                                 arg = bv_->getLyXText()->selectionAsString(buffer_, false);
1933                                 // FIXME: where is getLyXText()->unselect(bv_) ?
1934                         }
1935                 }
1936
1937                 bv_->owner()->getDialogs().showThesaurus(arg);
1938         }
1939                 break;
1940
1941         case LFUN_DATE_INSERT:  // jdblair: date-insert cmd
1942         {
1943                 time_t now_time_t = time(NULL);
1944                 struct tm * now_tm = localtime(&now_time_t);
1945                 setlocale(LC_TIME, "");
1946                 string arg;
1947                 if (!ev.argument.empty())
1948                         arg = ev.argument;
1949                 else
1950                         arg = lyxrc.date_insert_format;
1951                 char datetmp[32];
1952                 int const datetmp_len =
1953                         ::strftime(datetmp, 32, arg.c_str(), now_tm);
1954
1955                 LyXText * lt = bv_->getLyXText();
1956
1957                 for (int i = 0; i < datetmp_len; i++) {
1958                         lt->insertChar(bv_, datetmp[i]);
1959                         update(lt,
1960                                BufferView::SELECT
1961                                | BufferView::FITCUR
1962                                | BufferView::CHANGE);
1963                 }
1964
1965                 lt->selection.cursor = lt->cursor;
1966                 moveCursorUpdate(false);
1967         }
1968         break;
1969
1970         case LFUN_UNKNOWN_ACTION:
1971                 ev.errorMessage(N_("Unknown function!"));
1972                 break;
1973
1974         default:
1975                 FuncRequest cmd = ev;
1976                 cmd.setView(bv_);
1977                 return bv_->getLyXText()->dispatch(cmd);
1978         } // end of switch
1979
1980         return true;
1981 }
1982
1983
1984 void BufferView::Pimpl::smartQuote()
1985 {
1986         LyXText const * lt = bv_->getLyXText();
1987         Paragraph const * par = lt->cursor.par();
1988         pos_type pos = lt->cursor.pos();
1989         char c;
1990
1991         if (!pos
1992             || (par->isInset(pos - 1)
1993                 && par->getInset(pos - 1)->isSpace()))
1994                 c = ' ';
1995         else
1996                 c = par->getChar(pos - 1);
1997
1998         hideCursor();
1999
2000         LyXLayout_ptr const & style = par->layout();
2001
2002         if (style->pass_thru ||
2003             par->getFontSettings(buffer_->params,
2004                                  pos).language()->lang() == "hebrew" ||
2005                 (!insertInset(new InsetQuotes(c, buffer_->params))))
2006                 bv_->owner()->dispatch(FuncRequest(LFUN_SELFINSERT, "\""));
2007 }
2008
2009
2010 void BufferView::Pimpl::insertAndEditInset(Inset * inset)
2011 {
2012 #if 0
2013         if (insertInset(inset))
2014                 inset->edit(bv_);
2015         else
2016                 delete inset;
2017 #else
2018         bool gotsel = false;
2019
2020         if (bv_->getLyXText()->selection.set()) {
2021                 bv_->getLyXText()->cutSelection(bv_, true, false);
2022                 gotsel = true;
2023         }
2024
2025         if (insertInset(inset)) {
2026                 inset->edit(bv_);
2027                 if (gotsel)
2028                         owner_->dispatch(FuncRequest(LFUN_PASTESELECTION));
2029         }
2030         else
2031                 delete inset;
2032 #endif
2033 }
2034
2035
2036 // Open and lock an updatable inset
2037 bool BufferView::Pimpl::open_new_inset(UpdatableInset * new_inset, bool behind)
2038 {
2039         LyXText * lt = bv_->getLyXText();
2040
2041         beforeChange(lt);
2042         finishUndo();
2043         if (!insertInset(new_inset)) {
2044                 delete new_inset;
2045                 return false;
2046         }
2047         new_inset->edit(bv_, !behind);
2048         return true;
2049 }
2050
2051
2052 bool BufferView::Pimpl::insertInset(Inset * inset, string const & lout)
2053 {
2054         // if we are in a locking inset we should try to insert the
2055         // inset there otherwise this is a illegal function now
2056         if (bv_->theLockingInset()) {
2057                 if (bv_->theLockingInset()->insetAllowed(inset))
2058                     return bv_->theLockingInset()->insertInset(bv_, inset);
2059                 return false;
2060         }
2061
2062         // not quite sure if we want this...
2063         setCursorParUndo(bv_);
2064         freezeUndo();
2065
2066         beforeChange(bv_->text);
2067         if (!lout.empty()) {
2068                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
2069                 bv_->text->breakParagraph(bv_);
2070                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2071
2072                 if (!bv_->text->cursor.par()->empty()) {
2073                         bv_->text->cursorLeft(bv_);
2074
2075                         bv_->text->breakParagraph(bv_);
2076                         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2077                 }
2078
2079                 string lres = lout;
2080                 LyXTextClass const & tclass =
2081                         buffer_->params.getLyXTextClass();
2082                 bool hasLayout = tclass.hasLayout(lres);
2083                 string lay = tclass.defaultLayoutName();
2084
2085                 if (hasLayout != false) {
2086                         // layout found
2087                         lay = lres;
2088                 } else {
2089                         // layout not fount using default
2090                         lay = tclass.defaultLayoutName();
2091                 }
2092
2093                 bv_->text->setLayout(bv_, lay);
2094
2095                 bv_->text->setParagraph(bv_, 0, 0,
2096                                    0, 0,
2097                                    VSpace(VSpace::NONE), VSpace(VSpace::NONE),
2098                                    Spacing(),
2099                                    LYX_ALIGN_LAYOUT,
2100                                    string(),
2101                                    0);
2102                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2103         }
2104
2105         bv_->text->insertInset(bv_, inset);
2106         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2107
2108         unFreezeUndo();
2109         return true;
2110 }
2111
2112
2113 void BufferView::Pimpl::updateInset(Inset * inset, bool mark_dirty)
2114 {
2115         if (!inset || !available())
2116                 return;
2117
2118         // first check for locking insets
2119         if (bv_->theLockingInset()) {
2120                 if (bv_->theLockingInset() == inset) {
2121                         if (bv_->text->updateInset(bv_, inset)) {
2122                                 update();
2123                                 if (mark_dirty) {
2124                                         buffer_->markDirty();
2125                                 }
2126                                 updateScrollbar();
2127                                 return;
2128                         }
2129                 } else if (bv_->theLockingInset()->updateInsetInInset(bv_, inset)) {
2130                         if (bv_->text->updateInset(bv_,  bv_->theLockingInset())) {
2131                                 update();
2132                                 if (mark_dirty) {
2133                                         buffer_->markDirty();
2134                                 }
2135                                 updateScrollbar();
2136                                 return;
2137                         }
2138                 }
2139         }
2140
2141         // then check if the inset is a top_level inset (has no owner)
2142         // if yes do the update as always otherwise we have to update the
2143         // toplevel inset where this inset is inside
2144         Inset * tl_inset = inset;
2145         while (tl_inset->owner())
2146                 tl_inset = tl_inset->owner();
2147         hideCursor();
2148         if (tl_inset == inset) {
2149                 update(bv_->text, BufferView::UPDATE);
2150                 if (bv_->text->updateInset(bv_, inset)) {
2151                         if (mark_dirty) {
2152                                 update(bv_->text,
2153                                        BufferView::SELECT
2154                                        | BufferView::FITCUR
2155                                        | BufferView::CHANGE);
2156                         } else {
2157                                 update(bv_->text, SELECT);
2158                         }
2159                         return;
2160                 }
2161         } else if (static_cast<UpdatableInset *>(tl_inset)
2162                            ->updateInsetInInset(bv_, inset))
2163         {
2164                 if (bv_->text->updateInset(bv_, tl_inset)) {
2165                         update();
2166                         updateScrollbar();
2167                 }
2168         }
2169 }
2170
2171
2172 void BufferView::Pimpl::gotoInset(vector<Inset::Code> const & codes,
2173                                   bool same_content)
2174 {
2175         if (!available()) return;
2176
2177         hideCursor();
2178         beforeChange(bv_->text);
2179         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
2180
2181         LyXCursor const & cursor = bv_->text->cursor;
2182
2183         string contents;
2184         if (same_content &&
2185             cursor.par()->isInset(cursor.pos())) {
2186                 Inset const * inset = cursor.par()->getInset(cursor.pos());
2187                 if (find(codes.begin(), codes.end(), inset->lyxCode())
2188                     != codes.end())
2189                         contents =
2190                                 static_cast<InsetCommand const *>(inset)->getContents();
2191         }
2192
2193
2194         if (!bv_->text->gotoNextInset(bv_, codes, contents)) {
2195                 if (bv_->text->cursor.pos()
2196                     || bv_->text->cursor.par() != bv_->text->ownerParagraph()) {
2197                         LyXCursor tmp = bv_->text->cursor;
2198                         bv_->text->cursor.par(bv_->text->ownerParagraph());
2199                         bv_->text->cursor.pos(0);
2200                         if (!bv_->text->gotoNextInset(bv_, codes, contents)) {
2201                                 bv_->text->cursor = tmp;
2202                                 bv_->owner()->message(_("No more insets"));
2203                         }
2204                 } else {
2205                         bv_->owner()->message(_("No more insets"));
2206                 }
2207         }
2208         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
2209         bv_->text->selection.cursor = bv_->text->cursor;
2210 }
2211
2212
2213 void BufferView::Pimpl::gotoInset(Inset::Code code, bool same_content)
2214 {
2215         gotoInset(vector<Inset::Code>(1, code), same_content);
2216 }