]> git.lyx.org Git - lyx.git/blob - src/BufferView_pimpl.C
Hold on to your hats.
[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 #include "BufferView_pimpl.h"
12 #include "frontends/WorkArea.h"
13 #include "frontends/screen.h"
14 #include "frontends/LyXScreenFactory.h"
15 #include "frontends/WorkAreaFactory.h"
16 #include "frontends/Dialogs.h"
17 #include "frontends/Alert.h"
18 #include "frontends/FileDialog.h"
19 #include "frontends/mouse_state.h"
20 #include "lyxtext.h"
21 #include "lyxrow.h"
22 #include "paragraph.h"
23 #include "frontends/LyXView.h"
24 #include "commandtags.h"
25 #include "lyxfunc.h"
26 #include "debug.h"
27 #include "bufferview_funcs.h"
28 #include "TextCache.h"
29 #include "bufferlist.h"
30 #include "lyxrc.h"
31 #include "intl.h"
32 // added for Dispatch functions
33 #include "lyx_cb.h"
34 #include "lyx_main.h"
35 #include "FloatList.h"
36 #include "gettext.h"
37 #include "ParagraphParameters.h"
38 #include "undo_funcs.h"
39 #include "funcrequest.h"
40 #include "iterators.h"
41 #include "lyxfind.h"
42
43 #include "insets/insetbibitem.h"
44 #include "insets/insetbibtex.h"
45 #include "insets/insetcite.h"
46 #include "insets/insetert.h"
47 #include "insets/insetfloatlist.h"
48 #include "insets/insetgraphics.h"
49 #include "insets/insetinclude.h"
50 #include "insets/insetindex.h"
51 #include "insets/insetlatexaccent.h"
52 #include "insets/insetmarginal.h"
53 #include "insets/insetref.h"
54 #include "insets/insettext.h"
55 #include "insets/insettoc.h"
56 #include "insets/inseturl.h"
57
58 #include "mathed/formulabase.h"
59
60 #include "graphics/Previews.h"
61
62 #include "support/LAssert.h"
63 #include "support/lstrings.h"
64 #include "support/filetools.h"
65
66 #include <boost/bind.hpp>
67 #include <boost/signals/connection.hpp>
68 #include "BoostFormat.h"
69
70 #include <unistd.h>
71 #include <sys/wait.h>
72
73
74 using std::vector;
75 using std::find_if;
76 using std::find;
77 using std::pair;
78 using std::endl;
79 using std::make_pair;
80 using std::min;
81
82 using lyx::pos_type;
83
84 extern BufferList bufferlist;
85
86
87 namespace {
88
89 unsigned int const saved_positions_num = 20;
90
91 // All the below connection objects are needed because of a bug in some
92 // versions of GCC (<=2.96 are on the suspects list.) By having and assigning
93 // to these connections we avoid a segfault upon startup, and also at exit.
94 // (Lgb)
95
96 boost::signals::connection dispatchcon;
97 boost::signals::connection timecon;
98 boost::signals::connection doccon;
99 boost::signals::connection resizecon;
100 boost::signals::connection kpresscon;
101 boost::signals::connection selectioncon;
102 boost::signals::connection lostcon;
103
104
105 } // anon namespace
106
107
108 BufferView::Pimpl::Pimpl(BufferView * bv, LyXView * owner,
109              int xpos, int ypos, int width, int height)
110         : bv_(bv), owner_(owner), buffer_(0), cursor_timeout(400),
111           using_xterm_cursor(false)
112 {
113         workarea_.reset(WorkAreaFactory::create(xpos, ypos, width, height));
114         screen_.reset(LyXScreenFactory::create(workarea()));
115
116         // Setup the signals
117         doccon = workarea().scrollDocView
118                 .connect(boost::bind(&BufferView::Pimpl::scrollDocView, this, _1));
119         resizecon = workarea().workAreaResize
120                 .connect(boost::bind(&BufferView::Pimpl::workAreaResize, this));
121         dispatchcon = workarea().dispatch
122                 .connect(boost::bind(&BufferView::Pimpl::dispatch, this, _1));
123         kpresscon = workarea().workAreaKeyPress
124                 .connect(boost::bind(&BufferView::Pimpl::workAreaKeyPress, this, _1, _2));
125         selectioncon = workarea().selectionRequested
126                 .connect(boost::bind(&BufferView::Pimpl::selectionRequested, this));
127         lostcon = workarea().selectionLost
128                 .connect(boost::bind(&BufferView::Pimpl::selectionLost, this));
129
130         timecon = cursor_timeout.timeout
131                 .connect(boost::bind(&BufferView::Pimpl::cursorToggle, this));
132         cursor_timeout.start();
133         saved_positions.resize(saved_positions_num);
134 }
135
136
137 WorkArea & BufferView::Pimpl::workarea() const
138 {
139         return *workarea_.get();
140 }
141
142
143 LyXScreen & BufferView::Pimpl::screen() const
144 {
145         return *screen_.get();
146 }
147
148
149 Painter & BufferView::Pimpl::painter() const
150 {
151         return workarea().getPainter();
152 }
153
154
155 void BufferView::Pimpl::buffer(Buffer * b)
156 {
157         lyxerr[Debug::INFO] << "Setting buffer in BufferView ("
158                             << b << ')' << endl;
159         if (buffer_) {
160                 buffer_->delUser(bv_);
161
162                 // Put the old text into the TextCache, but
163                 // only if the buffer is still loaded.
164                 // Also set the owner of the test to 0
165                 //              bv_->text->owner(0);
166                 textcache.add(buffer_, workarea().workWidth(), bv_->text);
167                 if (lyxerr.debugging())
168                         textcache.show(lyxerr, "BufferView::buffer");
169
170                 bv_->text = 0;
171         }
172
173         // set current buffer
174         buffer_ = b;
175
176         // if we're quitting lyx, don't bother updating stuff 
177         if (quitting)
178                 return; 
179
180         // if we are closing the buffer, use the first buffer as current
181         if (!buffer_) {
182                 buffer_ = bufferlist.first();
183         }
184
185         if (buffer_) {
186                 lyxerr[Debug::INFO] << "Buffer addr: " << buffer_ << endl;
187                 buffer_->addUser(bv_);
188
189                 // If we don't have a text object for this, we make one
190                 if (bv_->text == 0) {
191                         resizeCurrentBuffer();
192                 }
193
194                 // FIXME: needed when ?
195                 bv_->text->first_y =
196                         screen().topCursorVisible(bv_->text->cursor, bv_->text->first_y);
197
198                 // Similarly, buffer-dependent dialogs should be updated or
199                 // hidden. This should go here because some dialogs (eg ToC)
200                 // require bv_->text.
201                 owner_->getDialogs().updateBufferDependent(true);
202         } else {
203                 lyxerr[Debug::INFO] << "  No Buffer!" << endl;
204                 owner_->getDialogs().hideBufferDependent();
205
206                 // Also remove all remaining text's from the testcache.
207                 // (there should not be any!) (if there is any it is a
208                 // bug!)
209                 if (lyxerr.debugging())
210                         textcache.show(lyxerr, "buffer delete all");
211                 textcache.clear();
212         }
213
214         repaint();
215         updateScrollbar();
216         owner_->updateMenubar();
217         owner_->updateToolbar();
218         owner_->updateLayoutChoice();
219         owner_->updateWindowTitle();
220
221         if (grfx::Previews::activated() && buffer_)
222                 grfx::Previews::get().generateBufferPreviews(*buffer_);
223 }
224
225
226 bool BufferView::Pimpl::fitCursor()
227 {
228         bool ret;
229
230         if (bv_->theLockingInset()) {
231                 bv_->theLockingInset()->fitInsetCursor(bv_);
232                 ret = true;
233         } else {
234                 ret = screen().fitCursor(bv_->text, bv_);
235         }
236
237         bv_->owner()->getDialogs().updateParagraph();
238         if (ret)
239                 updateScrollbar();
240         return ret;
241 }
242
243
244 void BufferView::Pimpl::redoCurrentBuffer()
245 {
246         lyxerr[Debug::INFO] << "BufferView::redoCurrentBuffer" << endl;
247         if (buffer_ && bv_->text) {
248                 resizeCurrentBuffer();
249                 updateScrollbar();
250                 owner_->updateLayoutChoice();
251                 repaint();
252         }
253 }
254
255
256 int BufferView::Pimpl::resizeCurrentBuffer()
257 {
258         lyxerr[Debug::INFO] << "resizeCurrentBuffer" << endl;
259
260         Paragraph * par = 0;
261         Paragraph * selstartpar = 0;
262         Paragraph * selendpar = 0;
263         UpdatableInset * the_locking_inset = 0;
264
265         pos_type pos = 0;
266         pos_type selstartpos = 0;
267         pos_type selendpos = 0;
268         bool selection = false;
269         bool mark_set  = false;
270
271         owner_->busy(true);
272  
273         owner_->message(_("Formatting document..."));
274
275         if (bv_->text) {
276                 par = bv_->text->cursor.par();
277                 pos = bv_->text->cursor.pos();
278                 selstartpar = bv_->text->selection.start.par();
279                 selstartpos = bv_->text->selection.start.pos();
280                 selendpar = bv_->text->selection.end.par();
281                 selendpos = bv_->text->selection.end.pos();
282                 selection = bv_->text->selection.set();
283                 mark_set = bv_->text->selection.mark();
284                 the_locking_inset = bv_->theLockingInset();
285                 buffer_->resizeInsets(bv_);
286                 // I don't think the delete and new are necessary here we just could
287                 // call only init! (Jug 20020419)
288                 delete bv_->text;
289                 bv_->text = new LyXText(bv_);
290                 bv_->text->init(bv_);
291         } else {
292                 // See if we have a text in TextCache that fits
293                 // the new buffer_ with the correct width.
294                 bv_->text = textcache.findFit(buffer_, workarea().workWidth());
295                 if (bv_->text) {
296                         if (lyxerr.debugging()) {
297                                 lyxerr << "Found a LyXText that fits:\n";
298                                 textcache.show(lyxerr, make_pair(buffer_, make_pair(workarea().workWidth(), bv_->text)));
299                         }
300                         // Set the owner of the newly found text
301                         //      bv_->text->owner(bv_);
302                         if (lyxerr.debugging())
303                                 textcache.show(lyxerr, "resizeCurrentBuffer");
304
305                         buffer_->resizeInsets(bv_);
306                 } else {
307                         bv_->text = new LyXText(bv_);
308                         bv_->text->init(bv_);
309                         //buffer_->resizeInsets(bv_);
310                 }
311         }
312
313         if (par) {
314                 bv_->text->selection.set(true);
315                 // At this point just to avoid the Delete-Empty-Paragraph-
316                 // Mechanism when setting the cursor.
317                 bv_->text->selection.mark(mark_set);
318                 if (selection) {
319                         bv_->text->setCursor(bv_, selstartpar, selstartpos);
320                         bv_->text->selection.cursor = bv_->text->cursor;
321                         bv_->text->setCursor(bv_, selendpar, selendpos);
322                         bv_->text->setSelection(bv_);
323                         bv_->text->setCursor(bv_, par, pos);
324                 } else {
325                         bv_->text->setCursor(bv_, par, pos);
326                         bv_->text->selection.cursor = bv_->text->cursor;
327                         bv_->text->selection.set(false);
328                 }
329                 // remake the inset locking
330                 bv_->theLockingInset(the_locking_inset);
331         }
332
333         bv_->text->first_y = screen().topCursorVisible(bv_->text->cursor, bv_->text->first_y);
334
335         switchKeyMap();
336         owner_->busy(false);
337
338         updateScrollbar();
339
340         return 0;
341 }
342
343
344 void BufferView::Pimpl::repaint()
345 {
346         // Regenerate the screen.
347         screen().redraw(bv_->text, bv_);
348 }
349
350
351 void BufferView::Pimpl::updateScrollbar()
352 {
353         if (!bv_->text) {
354                 lyxerr[Debug::GUI] << "no text in updateScrollbar" << endl;
355                 workarea().setScrollbarParams(0, 0, 0);
356                 return;
357         }
358
359         LyXText const & t = *bv_->text;
360
361         lyxerr[Debug::GUI] << "Updating scrollbar: h " << t.height << ", first_y "
362                 << t.first_y << ", default height " << defaultRowHeight() << endl;
363
364         workarea().setScrollbarParams(t.height, t.first_y, defaultRowHeight());
365 }
366
367
368 void BufferView::Pimpl::scrollDocView(int value)
369 {
370         lyxerr[Debug::GUI] << "scrollDocView of " << value << endl;
371
372         if (!buffer_)
373                 return;
374
375         screen().draw(bv_->text, bv_, value);
376
377         if (!lyxrc.cursor_follows_scrollbar)
378                 return;
379
380         LyXText * vbt = bv_->text;
381
382         int const height = defaultRowHeight();
383         int const first = static_cast<int>((bv_->text->first_y + height));
384         int const last = static_cast<int>((bv_->text->first_y + workarea().workHeight() - height));
385
386         if (vbt->cursor.y() < first)
387                 vbt->setCursorFromCoordinates(bv_, 0, first);
388         else if (vbt->cursor.y() > last)
389                 vbt->setCursorFromCoordinates(bv_, 0, last);
390 }
391
392
393 void BufferView::Pimpl::scroll(int lines)
394 {
395         if (!buffer_) {
396                 return;
397         }
398
399         LyXText const * t = bv_->text;
400         int const line_height = defaultRowHeight();
401
402         // The new absolute coordinate
403         int new_first_y = t->first_y + lines * line_height;
404
405         // Restrict to a valid value
406         new_first_y = std::min(t->height - 4 * line_height, new_first_y);
407         new_first_y = std::max(0, new_first_y);
408
409         scrollDocView(new_first_y);
410
411         // Update the scrollbar.
412         workarea().setScrollbarParams(t->height, t->first_y, defaultRowHeight());
413 }
414
415
416 void BufferView::Pimpl::workAreaKeyPress(LyXKeySymPtr key,
417                                          key_modifier::state state)
418 {
419         bv_->owner()->getLyXFunc().processKeySym(key, state);
420 }
421
422
423 void BufferView::Pimpl::selectionRequested()
424 {
425         static string sel;
426
427         if (!available())
428                 return;
429
430         LyXText * text = bv_->getLyXText();
431
432         if (text->selection.set() &&
433                 (!bv_->text->xsel_cache.set() ||
434                  text->selection.start != bv_->text->xsel_cache.start ||
435                  text->selection.end != bv_->text->xsel_cache.end))
436         {
437                 bv_->text->xsel_cache = text->selection;
438                 sel = text->selectionAsString(bv_->buffer(), false);
439         } else if (!text->selection.set()) {
440                 sel = string();
441                 bv_->text->xsel_cache.set(false);
442         }
443         if (!sel.empty()) {
444                 workarea().putClipboard(sel);
445         }
446 }
447
448
449 void BufferView::Pimpl::selectionLost()
450 {
451         if (available()) {
452                 hideCursor();
453                 toggleSelection();
454                 bv_->getLyXText()->clearSelection();
455                 showCursor();
456                 bv_->text->xsel_cache.set(false);
457         }
458 }
459
460
461 void BufferView::Pimpl::workAreaResize()
462 {
463         static int work_area_width;
464         static int work_area_height;
465
466         bool const widthChange = workarea().workWidth() != work_area_width;
467         bool const heightChange = workarea().workHeight() != work_area_height;
468
469         // update from work area
470         work_area_width = workarea().workWidth();
471         work_area_height = workarea().workHeight();
472
473         if (buffer_ != 0) {
474                 if (widthChange) {
475                         // The visible LyXView need a resize
476                         resizeCurrentBuffer();
477
478                         // Remove all texts from the textcache
479                         // This is not _really_ what we want to do. What
480                         // we really want to do is to delete in textcache
481                         // that does not have a BufferView with matching
482                         // width, but as long as we have only one BufferView
483                         // deleting all gives the same result.
484                         if (lyxerr.debugging())
485                                 textcache.show(lyxerr, "Expose delete all");
486                         textcache.clear();
487                         // FIXME: this is already done in resizeCurrentBuffer() ??
488                         buffer_->resizeInsets(bv_);
489                 } else if (heightChange) {
490                         // fitCursor() ensures we don't jump back
491                         // to the start of the document on vertical
492                         // resize
493                         fitCursor();
494                 }
495         }
496
497         if (widthChange || heightChange) {
498                 repaint();
499         }
500
501         // always make sure that the scrollbar is sane.
502         updateScrollbar();
503         owner_->updateLayoutChoice();
504         return;
505 }
506
507
508 void BufferView::Pimpl::update()
509 {
510         if (!bv_->theLockingInset() || !bv_->theLockingInset()->nodraw()) {
511                 LyXText::text_status st = bv_->text->status();
512                 screen().update(bv_->text, bv_);
513                 bool fitc = false;
514                 while (bv_->text->status() == LyXText::CHANGED_IN_DRAW) {
515                         bv_->text->fullRebreak(bv_);
516                         st = LyXText::NEED_MORE_REFRESH;
517                         bv_->text->setCursor(bv_, bv_->text->cursor.par(),
518                                              bv_->text->cursor.pos());
519                         if (bv_->text->selection.set()) {
520                                 bv_->text->setCursor(bv_, bv_->text->selection.start,
521                                                      bv_->text->selection.start.par(),
522                                                      bv_->text->selection.start.pos());
523                                 bv_->text->setCursor(bv_, bv_->text->selection.end,
524                                                      bv_->text->selection.end.par(),
525                                                      bv_->text->selection.end.pos());
526                         }
527                         fitc = true;
528                         bv_->text->status(bv_, st);
529                         screen().update(bv_->text, bv_);
530                 }
531                 // do this here instead of in the screen::update because of
532                 // the above loop!
533                 bv_->text->status(bv_, LyXText::UNCHANGED);
534                 if (fitc)
535                         fitCursor();
536         }
537 }
538
539 // Values used when calling update:
540 // -3 - update
541 // -2 - update, move sel_cursor if selection, fitcursor
542 // -1 - update, move sel_cursor if selection, fitcursor, mark dirty
543 //  0 - update, move sel_cursor if selection, fitcursor
544 //  1 - update, move sel_cursor if selection, fitcursor, mark dirty
545 //  3 - update, move sel_cursor if selection
546 //
547 // update -
548 // a simple redraw of the parts that need refresh
549 //
550 // move sel_cursor if selection -
551 // the text's sel_cursor is moved if there is selection is progress
552 //
553 // fitcursor -
554 // fitCursor() is called and the scrollbar updated
555 //
556 // mark dirty -
557 // the buffer is marked dirty.
558 //
559 // enum {
560 //       UPDATE = 0,
561 //       SELECT = 1,
562 //       FITCUR = 2,
563 //       CHANGE = 4
564 // };
565 //
566 // UPDATE_ONLY = UPDATE;
567 // UPDATE_SELECT = UPDATE | SELECT;
568 // UPDATE_SELECT_MOVE = UPDATE | SELECT | FITCUR;
569 // UPDATE_SELECT_MOVE_AFTER_CHANGE = UPDATE | SELECT | FITCUR | CHANGE;
570 //
571 // update(-3) -> update(0)         -> update(0) -> update(UPDATE)
572 // update(-2) -> update(1 + 2)     -> update(3) -> update(SELECT|FITCUR)
573 // update(-1) -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
574 // update(1)  -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
575 // update(3)  -> update(1)         -> update(1) -> update(SELECT)
576
577 void BufferView::Pimpl::update(LyXText * text, BufferView::UpdateCodes f)
578 {
579         owner_->updateLayoutChoice();
580
581         if (!text->selection.set() && (f & SELECT)) {
582                 text->selection.cursor = text->cursor;
583         }
584
585         text->fullRebreak(bv_);
586
587         if (text->inset_owner) {
588                 text->inset_owner->setUpdateStatus(bv_, InsetText::NONE);
589                 updateInset(text->inset_owner, false);
590         } else {
591                 update();
592         }
593
594         if ((f & FITCUR)) {
595                 fitCursor();
596         }
597
598         if ((f & CHANGE)) {
599                 buffer_->markDirty();
600         }
601 }
602
603
604 // Callback for cursor timer
605 void BufferView::Pimpl::cursorToggle()
606 {
607         if (!buffer_) {
608                 cursor_timeout.restart();
609                 return;
610         }
611
612         if (!bv_->theLockingInset()) {
613                 screen().cursorToggle(bv_);
614         } else {
615                 bv_->theLockingInset()->toggleInsetCursor(bv_);
616         }
617
618         cursor_timeout.restart();
619 }
620
621
622 bool BufferView::Pimpl::available() const
623 {
624         if (buffer_ && bv_->text)
625                 return true;
626         return false;
627 }
628
629
630 Change const BufferView::Pimpl::getCurrentChange()
631 {
632         if (!bv_->buffer()->params.tracking_changes) 
633                 return Change(Change::UNCHANGED);
634
635         LyXText * t(bv_->getLyXText());
636  
637         if (!t->selection.set())
638                 return Change(Change::UNCHANGED);
639  
640         LyXCursor const & cur(t->selection.start);
641         return cur.par()->lookupChangeFull(cur.pos());
642 }
643
644
645 void BufferView::Pimpl::beforeChange(LyXText * text)
646 {
647         toggleSelection();
648         text->clearSelection();
649 }
650
651
652 void BufferView::Pimpl::savePosition(unsigned int i)
653 {
654         if (i >= saved_positions_num)
655                 return;
656         saved_positions[i] = Position(buffer_->fileName(),
657                                       bv_->text->cursor.par()->id(),
658                                       bv_->text->cursor.pos());
659         if (i > 0) {
660                 ostringstream str;
661 #if USE_BOOST_FORMAT
662                 str << boost::format(_("Saved bookmark %1$d")) % i;
663 #else
664                 str << _("Saved bookmark ") << i;
665 #endif
666                 owner_->message(STRCONV(str.str()));
667         }
668 }
669
670
671 void BufferView::Pimpl::restorePosition(unsigned int i)
672 {
673         if (i >= saved_positions_num)
674                 return;
675
676         string const fname = saved_positions[i].filename;
677
678         beforeChange(bv_->text);
679
680         if (fname != buffer_->fileName()) {
681                 Buffer * b = bufferlist.exists(fname) ?
682                         bufferlist.getBuffer(fname) :
683                         bufferlist.loadLyXFile(fname); // don't ask, just load it
684                 if (b != 0) buffer(b);
685         }
686
687         Paragraph * par = buffer_->getParFromID(saved_positions[i].par_id);
688         if (!par)
689                 return;
690
691         bv_->text->setCursor(bv_, par,
692                              min(par->size(), saved_positions[i].par_pos));
693
694         update(bv_->text, BufferView::SELECT | BufferView::FITCUR);
695         if (i > 0) {
696                 ostringstream str;
697 #if USE_BOOST_FORMAT
698                 str << boost::format(_("Moved to bookmark %1$d")) % i;
699 #else
700                 str << _("Moved to bookmark ") << i;
701 #endif
702                 owner_->message(STRCONV(str.str()));
703         }
704 }
705
706
707 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
708 {
709         if (i >= saved_positions_num)
710                 return false;
711
712         return !saved_positions[i].filename.empty();
713 }
714
715
716 void BufferView::Pimpl::switchKeyMap()
717 {
718         if (!lyxrc.rtl_support)
719                 return;
720
721         LyXText * text = bv_->getLyXText();
722         if (text->real_current_font.isRightToLeft()
723             && !(bv_->theLockingInset()
724                  && bv_->theLockingInset()->lyxCode() == Inset::ERT_CODE))
725         {
726                 if (owner_->getIntl().keymap == Intl::PRIMARY)
727                         owner_->getIntl().KeyMapSec();
728         } else {
729                 if (owner_->getIntl().keymap == Intl::SECONDARY)
730                         owner_->getIntl().KeyMapPrim();
731         }
732 }
733
734
735 void BufferView::Pimpl::insetUnlock()
736 {
737         if (bv_->theLockingInset()) {
738                 bv_->theLockingInset()->insetUnlock(bv_);
739                 bv_->theLockingInset(0);
740                 finishUndo();
741         }
742 }
743
744
745 void BufferView::Pimpl::showCursor()
746 {
747         if (bv_->theLockingInset())
748                 bv_->theLockingInset()->showInsetCursor(bv_);
749         else
750                 screen().showCursor(bv_->text, bv_);
751 }
752
753
754 void BufferView::Pimpl::hideCursor()
755 {
756         if (!bv_->theLockingInset())
757                 screen().hideCursor();
758 }
759
760
761 void BufferView::Pimpl::toggleSelection(bool b)
762 {
763         if (bv_->theLockingInset())
764                 bv_->theLockingInset()->toggleSelection(bv_, b);
765         screen().toggleSelection(bv_->text, bv_, b);
766 }
767
768
769 void BufferView::Pimpl::toggleToggle()
770 {
771         screen().toggleToggle(bv_->text, bv_);
772 }
773
774
775 void BufferView::Pimpl::center()
776 {
777         LyXText * t = bv_->text;
778
779         beforeChange(t);
780         int const half_height = workarea().workHeight() / 2;
781         int new_y = 0;
782
783         if (t->cursor.y() > half_height) {
784                 new_y = t->cursor.y() - half_height;
785         }
786
787         // FIXME: can we do this w/o calling screen directly ?
788         // This updates first_y but means the fitCursor() call
789         // from the update(FITCUR) doesn't realise that we might
790         // have moved (e.g. from GOTOPARAGRAPH), so doesn't cause
791         // the scrollbar to be updated as it should, so we have
792         // to do it manually. Any operation that does a center()
793         // and also might have moved first_y must make sure to call
794         // updateScrollbar() currently. Never mind that this is a
795         // pretty obfuscated way of updating t->first_y
796         screen().draw(t, bv_, new_y);
797
798         update(t, BufferView::SELECT | BufferView::FITCUR);
799 }
800
801
802 void BufferView::Pimpl::stuffClipboard(string const & stuff) const
803 {
804         workarea().putClipboard(stuff);
805 }
806
807
808 /*
809  * Dispatch functions for actions which can be valid for BufferView->text
810  * and/or InsetText->text!!!
811  */
812
813
814 Inset * BufferView::Pimpl::getInsetByCode(Inset::Code code)
815 {
816 #if 0
817         LyXCursor cursor = bv_->getLyXText()->cursor;
818         Buffer::inset_iterator it =
819                 find_if(Buffer::inset_iterator(
820                         cursor.par(), cursor.pos()),
821                         buffer_->inset_iterator_end(),
822                         lyx::compare_memfun(&Inset::lyxCode, code));
823         return it != buffer_->inset_iterator_end() ? (*it) : 0;
824 #else
825         // Ok, this is a little bit too brute force but it
826         // should work for now. Better infrastructure is comming. (Lgb)
827
828         Buffer * b = bv_->buffer();
829         LyXCursor cursor = bv_->getLyXText()->cursor;
830
831         Buffer::inset_iterator beg = b->inset_iterator_begin();
832         Buffer::inset_iterator end = b->inset_iterator_end();
833
834         bool cursor_par_seen = false;
835
836         for (; beg != end; ++beg) {
837                 if (beg.getPar() == cursor.par()) {
838                         cursor_par_seen = true;
839                 }
840                 if (cursor_par_seen) {
841                         if (beg.getPar() == cursor.par()
842                             && beg.getPos() >= cursor.pos()) {
843                                 break;
844                         } else if (beg.getPar() != cursor.par()) {
845                                 break;
846                         }
847                 }
848
849         }
850         if (beg != end) {
851                 // Now find the first inset that matches code.
852                 for (; beg != end; ++beg) {
853                         if (beg->lyxCode() == code) {
854                                 return &(*beg);
855                         }
856                 }
857         }
858         return 0;
859 #endif
860 }
861
862
863 void BufferView::Pimpl::MenuInsertLyXFile(string const & filen)
864 {
865         string filename = filen;
866
867         if (filename.empty()) {
868                 // Launch a file browser
869                 string initpath = lyxrc.document_path;
870
871                 if (available()) {
872                         string const trypath = owner_->buffer()->filePath();
873                         // If directory is writeable, use this as default.
874                         if (IsDirWriteable(trypath))
875                                 initpath = trypath;
876                 }
877
878                 FileDialog fileDlg(_("Select LyX document to insert"),
879                         LFUN_FILE_INSERT,
880                         make_pair(string(_("Documents|#o#O")),
881                                   string(lyxrc.document_path)),
882                         make_pair(string(_("Examples|#E#e")),
883                                   string(AddPath(system_lyxdir, "examples"))));
884
885                 FileDialog::Result result =
886                         fileDlg.open(initpath,
887                                        _("*.lyx| LyX Documents (*.lyx)"));
888
889                 if (result.first == FileDialog::Later)
890                         return;
891
892                 filename = result.second;
893
894                 // check selected filename
895                 if (filename.empty()) {
896                         owner_->message(_("Canceled."));
897                         return;
898                 }
899         }
900
901         // get absolute path of file and add ".lyx" to the filename if
902         // necessary
903         filename = FileSearch(string(), filename, "lyx");
904
905         string const disp_fn(MakeDisplayPath(filename));
906
907         ostringstream s1;
908 #if USE_BOOST_FORMAT
909         s1 << boost::format(_("Inserting document %1$s...")) % disp_fn;
910 #else
911         s1 << _("Inserting document ") << disp_fn << _("...");
912 #endif
913         owner_->message(STRCONV(s1.str()));
914         bool const res = bv_->insertLyXFile(filename);
915         if (res) {
916                 ostringstream str;
917 #if USE_BOOST_FORMAT
918                 str << boost::format(_("Document %1$s inserted.")) % disp_fn;
919 #else
920                 str << _("Document ") << disp_fn << _(" inserted.");
921 #endif
922                 owner_->message(STRCONV(str.str()));
923         } else {
924                 ostringstream str;
925 #if USE_BOOST_FORMAT
926                 str << boost::format(_("Could not insert document %1$s")) % disp_fn;
927 #else
928                 str << _("Could not insert document ") << disp_fn;
929 #endif
930                 owner_->message(STRCONV(str.str()));
931         }
932 }
933
934
935 void BufferView::Pimpl::trackChanges()
936 {
937         Buffer * buf(bv_->buffer());
938         bool const tracking(buf->params.tracking_changes);
939
940         if (!tracking) {
941                 ParIterator const end = buf->par_iterator_end();
942                 for (ParIterator it = buf->par_iterator_begin(); it != end; ++it) {
943                         (*it)->trackChanges();
944                 }
945                 buf->params.tracking_changes = true;
946
947                 // we cannot allow undos beyond the freeze point
948                 buf->undostack.clear();
949         } else {
950                 bv_->update(bv_->text, BufferView::SELECT | BufferView::FITCUR);
951                 bv_->text->setCursor(bv_, &(*buf->paragraphs.begin()), 0);
952 #warning changes FIXME 
953                 //moveCursorUpdate(false);
954
955                 bool found = lyxfind::findNextChange(bv_);
956                 if (found) {
957                         owner_->getDialogs().showMergeChanges();
958                         return;
959                 }
960
961                 ParIterator const end = buf->par_iterator_end();
962                 for (ParIterator it = buf->par_iterator_begin(); it != end; ++it) {
963                         (*it)->untrackChanges();
964                 }
965                 buf->params.tracking_changes = false;
966         }
967  
968         buf->redostack.clear();
969 }
970
971
972 bool BufferView::Pimpl::dispatch(FuncRequest const & ev)
973 {
974         lyxerr[Debug::ACTION] << "BufferView::Pimpl::Dispatch:"
975                 << " action[" << ev.action << ']'
976                 << " arg[" << ev.argument << ']'
977                 << " x[" << ev.x << ']'
978                 << " y[" << ev.y << ']'
979                 << " button[" << ev.button() << ']'
980                 << endl;
981
982         // e.g. Qt mouse press when no buffer
983         if (!buffer_)
984                 return false;
985
986         LyXTextClass const & tclass = buffer_->params.getLyXTextClass();
987
988         switch (ev.action) {
989
990         case LFUN_SCROLL_INSET:
991                 // this is not handled here as this function is only active
992                 // if we have a locking_inset and that one is (or contains)
993                 // a tabular-inset
994                 break;
995
996         case LFUN_INSET_GRAPHICS:
997         {
998                 Inset * new_inset = new InsetGraphics;
999                 if (!insertInset(new_inset)) {
1000                         delete new_inset;
1001                 } else {
1002                         // this is need because you don't use a inset->Edit()
1003                         updateInset(new_inset, true);
1004                         new_inset->edit(bv_);
1005                 }
1006                 break;
1007         }
1008
1009         case LFUN_LAYOUT_COPY:
1010                 bv_->copyEnvironment();
1011                 break;
1012
1013         case LFUN_LAYOUT_PASTE:
1014                 bv_->pasteEnvironment();
1015                 switchKeyMap();
1016                 break;
1017
1018         case LFUN_DEPTH_MIN:
1019                 changeDepth(bv_, bv_->getLyXText(), -1);
1020                 break;
1021
1022         case LFUN_DEPTH_PLUS:
1023                 changeDepth(bv_, bv_->getLyXText(), 1);
1024                 break;
1025
1026         case LFUN_FREE:
1027                 owner_->getDialogs().setUserFreeFont();
1028                 break;
1029
1030         case LFUN_FILE_INSERT:
1031                 MenuInsertLyXFile(ev.argument);
1032                 break;
1033
1034         case LFUN_FILE_INSERT_ASCII_PARA:
1035                 InsertAsciiFile(bv_, ev.argument, true);
1036                 break;
1037
1038         case LFUN_FILE_INSERT_ASCII:
1039                 InsertAsciiFile(bv_, ev.argument, false);
1040                 break;
1041
1042         case LFUN_LANGUAGE:
1043                 lang(bv_, ev.argument);
1044                 switchKeyMap();
1045                 owner_->view_state_changed();
1046                 break;
1047
1048         case LFUN_EMPH:
1049                 emph(bv_);
1050                 owner_->view_state_changed();
1051                 break;
1052
1053         case LFUN_BOLD:
1054                 bold(bv_);
1055                 owner_->view_state_changed();
1056                 break;
1057
1058         case LFUN_NOUN:
1059                 noun(bv_);
1060                 owner_->view_state_changed();
1061                 break;
1062
1063         case LFUN_CODE:
1064                 code(bv_);
1065                 owner_->view_state_changed();
1066                 break;
1067
1068         case LFUN_SANS:
1069                 sans(bv_);
1070                 owner_->view_state_changed();
1071                 break;
1072
1073         case LFUN_ROMAN:
1074                 roman(bv_);
1075                 owner_->view_state_changed();
1076                 break;
1077
1078         case LFUN_DEFAULT:
1079                 styleReset(bv_);
1080                 owner_->view_state_changed();
1081                 break;
1082
1083         case LFUN_UNDERLINE:
1084                 underline(bv_);
1085                 owner_->view_state_changed();
1086                 break;
1087
1088         case LFUN_FONT_SIZE:
1089                 fontSize(bv_, ev.argument);
1090                 owner_->view_state_changed();
1091                 break;
1092
1093         case LFUN_FONT_STATE:
1094                 owner_->getLyXFunc().setMessage(currentState(bv_));
1095                 break;
1096
1097         case LFUN_INSERT_LABEL:
1098                 MenuInsertLabel(bv_, ev.argument);
1099                 break;
1100
1101         case LFUN_BOOKMARK_SAVE:
1102                 savePosition(strToUnsignedInt(ev.argument));
1103                 break;
1104
1105         case LFUN_BOOKMARK_GOTO:
1106                 restorePosition(strToUnsignedInt(ev.argument));
1107                 break;
1108
1109         case LFUN_REF_GOTO:
1110         {
1111                 string label = ev.argument;
1112                 if (label.empty()) {
1113                         InsetRef * inset =
1114                                 static_cast<InsetRef*>(getInsetByCode(Inset::REF_CODE));
1115                         if (inset) {
1116                                 label = inset->getContents();
1117                                 savePosition(0);
1118                         }
1119                 }
1120
1121                 if (!label.empty()) {
1122                         //bv_->savePosition(0);
1123                         if (!bv_->gotoLabel(label))
1124                                 Alert::alert(_("Error"),
1125                                            _("Couldn't find this label"),
1126                                            _("in current document."));
1127                 }
1128         }
1129         break;
1130
1131         // --- accented characters ---------------------------
1132
1133         case LFUN_UMLAUT:
1134         case LFUN_CIRCUMFLEX:
1135         case LFUN_GRAVE:
1136         case LFUN_ACUTE:
1137         case LFUN_TILDE:
1138         case LFUN_CEDILLA:
1139         case LFUN_MACRON:
1140         case LFUN_DOT:
1141         case LFUN_UNDERDOT:
1142         case LFUN_UNDERBAR:
1143         case LFUN_CARON:
1144         case LFUN_SPECIAL_CARON:
1145         case LFUN_BREVE:
1146         case LFUN_TIE:
1147         case LFUN_HUNG_UMLAUT:
1148         case LFUN_CIRCLE:
1149         case LFUN_OGONEK:
1150                 if (ev.argument.empty()) {
1151                         // As always...
1152                         owner_->getLyXFunc().handleKeyFunc(ev.action);
1153                 } else {
1154                         owner_->getLyXFunc().handleKeyFunc(ev.action);
1155                         owner_->getIntl().getTransManager()
1156                                 .TranslateAndInsert(ev.argument[0], bv_->getLyXText());
1157                         update(bv_->getLyXText(),
1158                                BufferView::SELECT
1159                                | BufferView::FITCUR
1160                                | BufferView::CHANGE);
1161                 }
1162                 break;
1163
1164         case LFUN_MATH_MACRO:
1165         case LFUN_MATH_DELIM:
1166         case LFUN_INSERT_MATRIX:
1167         case LFUN_INSERT_MATH:
1168         case LFUN_MATH_IMPORT_SELECTION: // Imports LaTeX from the X selection
1169         case LFUN_MATH_DISPLAY:          // Open or create a displayed math inset
1170         case LFUN_MATH_MODE:             // Open or create an inlined math inset
1171         case LFUN_GREEK:                 // Insert a single greek letter
1172                 mathDispatch(FuncRequest(bv_, ev.action, ev.argument));
1173                 break;
1174
1175         case LFUN_BIBITEM_APPLY: {
1176                 InsetCommandParams params;
1177                 InsetCommandMailer::string2params(ev.argument, params);
1178
1179                 InsetBase * base =
1180                         owner_->getDialogs().getOpenInset("bibitem");
1181                 InsetBibitem * inset = 0;
1182                 if (base) {
1183                         inset = dynamic_cast<InsetBibitem *>(base);
1184                         if (!inset)
1185                                 break;
1186                         
1187                         if (params.getContents() !=
1188                             inset->params().getContents()) {
1189                                 bv_->ChangeCitationsIfUnique(
1190                                         inset->params().getContents(),
1191                                         params.getContents());
1192                         }
1193                         inset->setParams(params);
1194                 } else {
1195                         inset = new InsetBibitem(params);
1196                         if (!insertInset(inset)) {
1197                                 delete inset;
1198                                 break;
1199                         }
1200                 }
1201                 updateInset(inset, true);
1202
1203                 // We need to do a redraw because the maximum
1204                 // InsetBibitem width could have changed
1205 #warning please check you mean repaint() not update(),
1206 #warning and whether the repaint() is needed at all
1207                 bv_->repaint();
1208                 bv_->fitCursor();
1209         }
1210         break;
1211
1212         case LFUN_BIBTEX_APPLY: {
1213                 InsetCommandParams params;
1214                 InsetCommandMailer::string2params(ev.argument, params);
1215
1216                 InsetBase * base =
1217                         owner_->getDialogs().getOpenInset("bibtex");
1218                 InsetBibtex * inset = 0;
1219                 if (base) {
1220                         inset = dynamic_cast<InsetBibtex *>(base);
1221                         if (!inset)
1222                                 break;
1223
1224                         if (params.getContents() !=
1225                             inset->params().getContents()) {
1226                                 bv_->ChangeCitationsIfUnique(
1227                                         inset->params().getContents(),
1228                                         params.getContents());
1229                         }
1230                         inset->setParams(params);
1231                 } else {
1232                         inset = new InsetBibtex(params);
1233                         if (!insertInset(inset)) {
1234                                 delete inset;
1235                                 break;
1236                         }
1237                 }
1238                 updateInset(inset, true);
1239         }
1240         break;
1241
1242         case LFUN_CITATION_APPLY: {
1243                 InsetCommandParams params;
1244                 InsetCommandMailer::string2params(ev.argument, params);
1245
1246                 InsetBase * base =
1247                         owner_->getDialogs().getOpenInset("citation");
1248                 InsetCitation * inset = 0;
1249                 if (base) {
1250                         inset = dynamic_cast<InsetCitation *>(base);
1251                         if (!inset)
1252                                 break;
1253
1254                         inset->setParams(params);
1255                 } else {
1256                         inset = new InsetCitation(params);
1257                         if (!insertInset(inset)) {
1258                                 delete inset;
1259                                 break;
1260                         } else {
1261                                 inset->setLoadingBuffer(bv_->buffer(), false);
1262                         }
1263                 }
1264                 updateInset(inset, true);
1265         }
1266         break;
1267
1268         case LFUN_ERT_APPLY: {
1269                 InsetBase * base = owner_->getDialogs().getOpenInset("ert");
1270                 InsetERT * inset = 0;
1271                 if (base) {
1272                         inset = dynamic_cast<InsetERT *>(base);
1273                         if (!inset)
1274                                 break;
1275                 } else {
1276                         inset = new InsetERT(bv_->buffer()->params);
1277                         if (!insertInset(inset)) {
1278                                 delete inset;
1279                                 break;
1280                         }
1281                 }
1282
1283                 InsetERT::ERTStatus status;
1284                 InsetERTMailer::string2params(ev.argument, status);
1285
1286                 inset->status(bv_, status);
1287                 updateInset(inset, true);
1288         }
1289         break;
1290
1291         case LFUN_INDEX_APPLY: {
1292                 InsetCommandParams params;
1293                 InsetCommandMailer::string2params(ev.argument, params);
1294
1295                 InsetBase * base = owner_->getDialogs().getOpenInset("index");
1296                 InsetIndex * inset = 0;
1297                 if (base) {
1298                         inset = dynamic_cast<InsetIndex *>(base);
1299                         if (!inset)
1300                                 break;
1301
1302                         inset->setParams(params);
1303                 } else {
1304                         InsetIndex * inset = new InsetIndex(params);
1305                         if (!insertInset(inset)) {
1306                                 delete inset;
1307                                 break;
1308                         }
1309                 }
1310                 updateInset(inset, true);
1311         }
1312         break;
1313
1314         case LFUN_REF_APPLY: {
1315                 InsetCommandParams params;
1316                 InsetCommandMailer::string2params(ev.argument, params);
1317
1318                 InsetBase * base = owner_->getDialogs().getOpenInset("ref");
1319                 InsetRef * inset = 0;
1320                 if (base) {
1321                         inset = dynamic_cast<InsetRef *>(base);
1322                         if (!inset)
1323                                 break;
1324
1325                         inset->setParams(params);
1326                 } else {
1327                         InsetRef * inset = new InsetRef(params, *buffer_);
1328                         if (!insertInset(inset)) {
1329                                 delete inset;
1330                                 break;
1331                         }
1332                 }
1333                 updateInset(inset, true);
1334         }
1335         break;
1336
1337         case LFUN_TOC_APPLY: {
1338                 InsetCommandParams params;
1339                 InsetCommandMailer::string2params(ev.argument, params);
1340
1341                 InsetBase * base = owner_->getDialogs().getOpenInset("toc");
1342                 InsetTOC * inset = 0;
1343                 if (base) {
1344                         InsetTOC * inset = dynamic_cast<InsetTOC *>(base);
1345                         if (!inset)
1346                                 break;
1347
1348                         inset->setParams(params);
1349                 } else {
1350                         InsetTOC * inset = new InsetTOC(params);
1351                         if (!insertInset(inset)) {
1352                                 delete inset;
1353                                 break;
1354                         }
1355                 }
1356                 updateInset(inset, true);
1357         }
1358         break;
1359
1360         case LFUN_URL_APPLY: {
1361                 InsetCommandParams params;
1362                 InsetCommandMailer::string2params(ev.argument, params);
1363
1364                 InsetBase * base = owner_->getDialogs().getOpenInset("url");
1365                 InsetUrl * inset = 0;
1366                 if (base) {
1367                         inset = dynamic_cast<InsetUrl *>(base);
1368                         if (!inset)
1369                                 break;
1370
1371                         inset->setParams(params);
1372                 } else {
1373                         InsetUrl * inset = new InsetUrl(params);
1374                         if (!insertInset(inset)) {
1375                                 delete inset;
1376                                 break;
1377                         }
1378                 }
1379                 updateInset(inset, true);
1380         }
1381         break;
1382
1383         case LFUN_CHILD_INSERT:
1384         {
1385                 InsetInclude::Params p;
1386                 if (!ev.argument.empty())
1387                         p.cparams.setFromString(ev.argument);
1388                 p.masterFilename_ = buffer_->fileName();
1389
1390                 InsetInclude * inset = new InsetInclude(p);
1391                 if (!insertInset(inset))
1392                         delete inset;
1393                 else {
1394                         updateInset(inset, true);
1395                         bv_->owner()->getDialogs().showInclude(inset);
1396                 }
1397         }
1398         break;
1399
1400         case LFUN_FLOAT_LIST:
1401                 if (tclass.floats().typeExist(ev.argument)) {
1402                         Inset * inset = new InsetFloatList(ev.argument);
1403                         if (!insertInset(inset, tclass.defaultLayoutName()))
1404                                 delete inset;
1405                 } else {
1406                         lyxerr << "Non-existent float type: "
1407                                << ev.argument << endl;
1408                 }
1409                 break;
1410
1411         case LFUN_THESAURUS_ENTRY:
1412         {
1413                 string arg = ev.argument;
1414
1415                 if (arg.empty()) {
1416                         arg = bv_->getLyXText()->selectionAsString(buffer_,
1417                                                                    false);
1418
1419                         // FIXME
1420                         if (arg.size() > 100 || arg.empty()) {
1421                                 // Get word or selection
1422                                 bv_->getLyXText()->selectWordWhenUnderCursor(bv_, LyXText::WHOLE_WORD);
1423                                 arg = bv_->getLyXText()->selectionAsString(buffer_, false);
1424                                 // FIXME: where is getLyXText()->unselect(bv_) ?
1425                         }
1426                 }
1427
1428                 bv_->owner()->getDialogs().showThesaurus(arg);
1429         }
1430                 break;
1431
1432         case LFUN_TRACK_CHANGES:
1433                 trackChanges();
1434                 break;
1435  
1436         case LFUN_MERGE_CHANGES:
1437                 owner_->getDialogs().showMergeChanges();
1438                 break;
1439  
1440         case LFUN_ACCEPT_ALL_CHANGES: {
1441                 bv_->update(bv_->text, BufferView::SELECT | BufferView::FITCUR);
1442                 bv_->text->setCursor(bv_, &(*bv_->buffer()->paragraphs.begin()), 0);
1443 #warning FIXME changes 
1444                 //moveCursorUpdate(false);
1445
1446                 while (lyxfind::findNextChange(bv_)) {
1447                         bv_->getLyXText()->acceptChange(bv_);
1448                 }
1449                 update(bv_->text,
1450                         BufferView::SELECT | BufferView::FITCUR | BufferView::CHANGE);
1451                 break;
1452         }
1453  
1454         case LFUN_REJECT_ALL_CHANGES: {
1455                 bv_->update(bv_->text, BufferView::SELECT | BufferView::FITCUR);
1456                 bv_->text->setCursor(bv_, &(*bv_->buffer()->paragraphs.begin()), 0);
1457 #warning FIXME changes 
1458                 //moveCursorUpdate(false);
1459
1460                 while (lyxfind::findNextChange(bv_)) {
1461                         bv_->getLyXText()->rejectChange(bv_);
1462                 }
1463                 update(bv_->text,
1464                         BufferView::SELECT | BufferView::FITCUR | BufferView::CHANGE);
1465                 break;
1466         }
1467  
1468         case LFUN_ACCEPT_CHANGE: {
1469                 bv_->getLyXText()->acceptChange(bv_);
1470                 update(bv_->text,
1471                         BufferView::SELECT | BufferView::FITCUR | BufferView::CHANGE);
1472                 break;
1473         }
1474
1475         case LFUN_REJECT_CHANGE: {
1476                 bv_->getLyXText()->rejectChange(bv_);
1477                 update(bv_->text,
1478                         BufferView::SELECT | BufferView::FITCUR | BufferView::CHANGE);
1479                 break;
1480         }
1481  
1482         case LFUN_UNKNOWN_ACTION:
1483                 ev.errorMessage(N_("Unknown function!"));
1484                 break;
1485
1486         default:
1487                 return bv_->getLyXText()->dispatch(FuncRequest(ev, bv_));
1488         } // end of switch
1489
1490         return true;
1491 }
1492
1493
1494 bool BufferView::Pimpl::insertInset(Inset * inset, string const & lout)
1495 {
1496         // if we are in a locking inset we should try to insert the
1497         // inset there otherwise this is a illegal function now
1498         if (bv_->theLockingInset()) {
1499                 if (bv_->theLockingInset()->insetAllowed(inset))
1500                         return bv_->theLockingInset()->insertInset(bv_, inset);
1501                 return false;
1502         }
1503
1504         // not quite sure if we want this...
1505         setCursorParUndo(bv_);
1506         freezeUndo();
1507
1508         beforeChange(bv_->text);
1509         if (!lout.empty()) {
1510                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
1511                 bv_->text->breakParagraph(bv_);
1512                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1513
1514                 if (!bv_->text->cursor.par()->empty()) {
1515                         bv_->text->cursorLeft(bv_);
1516
1517                         bv_->text->breakParagraph(bv_);
1518                         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1519                 }
1520
1521                 string lres = lout;
1522                 LyXTextClass const & tclass =
1523                         buffer_->params.getLyXTextClass();
1524                 bool hasLayout = tclass.hasLayout(lres);
1525                 string lay = tclass.defaultLayoutName();
1526
1527                 if (hasLayout != false) {
1528                         // layout found
1529                         lay = lres;
1530                 } else {
1531                         // layout not fount using default
1532                         lay = tclass.defaultLayoutName();
1533                 }
1534
1535                 bv_->text->setLayout(bv_, lay);
1536
1537                 bv_->text->setParagraph(bv_, 0, 0,
1538                                    0, 0,
1539                                    VSpace(VSpace::NONE), VSpace(VSpace::NONE),
1540                                    Spacing(),
1541                                    LYX_ALIGN_LAYOUT,
1542                                    string(),
1543                                    0);
1544                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1545         }
1546
1547         bv_->text->insertInset(bv_, inset);
1548         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1549
1550         unFreezeUndo();
1551         return true;
1552 }
1553
1554
1555 void BufferView::Pimpl::updateInset(Inset * inset, bool mark_dirty)
1556 {
1557         if (!inset || !available())
1558                 return;
1559
1560         // first check for locking insets
1561         if (bv_->theLockingInset()) {
1562                 if (bv_->theLockingInset() == inset) {
1563                         if (bv_->text->updateInset(bv_, inset)) {
1564                                 update();
1565                                 if (mark_dirty) {
1566                                         buffer_->markDirty();
1567                                 }
1568                                 updateScrollbar();
1569                                 return;
1570                         }
1571                 } else if (bv_->theLockingInset()->updateInsetInInset(bv_, inset)) {
1572                         if (bv_->text->updateInset(bv_,  bv_->theLockingInset())) {
1573                                 update();
1574                                 if (mark_dirty) {
1575                                         buffer_->markDirty();
1576                                 }
1577                                 updateScrollbar();
1578                                 return;
1579                         }
1580                 }
1581         }
1582
1583         // then check if the inset is a top_level inset (has no owner)
1584         // if yes do the update as always otherwise we have to update the
1585         // toplevel inset where this inset is inside
1586         Inset * tl_inset = inset;
1587         while (tl_inset->owner())
1588                 tl_inset = tl_inset->owner();
1589         hideCursor();
1590         if (tl_inset == inset) {
1591                 update(bv_->text, BufferView::UPDATE);
1592                 if (bv_->text->updateInset(bv_, inset)) {
1593                         if (mark_dirty) {
1594                                 update(bv_->text,
1595                                        BufferView::SELECT
1596                                        | BufferView::FITCUR
1597                                        | BufferView::CHANGE);
1598                         } else {
1599                                 update(bv_->text, SELECT);
1600                         }
1601                         return;
1602                 }
1603         } else if (static_cast<UpdatableInset *>(tl_inset)
1604                            ->updateInsetInInset(bv_, inset))
1605         {
1606                 if (bv_->text->updateInset(bv_, tl_inset)) {
1607                         update();
1608                         updateScrollbar();
1609                 }
1610         }
1611 }