]> git.lyx.org Git - lyx.git/blob - src/BufferView.cpp
edea2eb3205fffd4216a53ce189c988a62d4856e
[lyx.git] / src / BufferView.cpp
1 /**
2  * \file BufferView.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author John Levon
9  * \author André Pönitz
10  * \author Jürgen Vigna
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "BufferView.h"
18
19 #include "BranchList.h"
20 #include "Buffer.h"
21 #include "buffer_funcs.h"
22 #include "BufferList.h"
23 #include "BufferParams.h"
24 #include "CoordCache.h"
25 #include "Cursor.h"
26 #include "CutAndPaste.h"
27 #include "DispatchResult.h"
28 #include "ErrorList.h"
29 #include "factory.h"
30 #include "FloatList.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
33 #include "Intl.h"
34 #include "InsetIterator.h"
35 #include "Language.h"
36 #include "LaTeXFeatures.h"
37 #include "LayoutFile.h"
38 #include "Length.h"
39 #include "Lexer.h"
40 #include "LyX.h"
41 #include "LyXAction.h"
42 #include "lyxfind.h"
43 #include "Layout.h"
44 #include "LyXRC.h"
45 #include "MetricsInfo.h"
46 #include "Paragraph.h"
47 #include "ParagraphParameters.h"
48 #include "ParIterator.h"
49 #include "RowPainter.h"
50 #include "Session.h"
51 #include "Text.h"
52 #include "TextClass.h"
53 #include "TextMetrics.h"
54 #include "TexRow.h"
55 #include "TocBackend.h"
56 #include "WordLangTuple.h"
57
58 #include "insets/InsetBibtex.h"
59 #include "insets/InsetCitation.h"
60 #include "insets/InsetCommand.h" // ChangeRefs
61 #include "insets/InsetExternal.h"
62 #include "insets/InsetGraphics.h"
63 #include "insets/InsetNote.h"
64 #include "insets/InsetRef.h"
65 #include "insets/InsetText.h"
66
67 #include "mathed/MathData.h"
68
69 #include "frontends/alert.h"
70 #include "frontends/Application.h"
71 #include "frontends/Delegates.h"
72 #include "frontends/FontMetrics.h"
73 #include "frontends/NullPainter.h"
74 #include "frontends/Painter.h"
75 #include "frontends/Selection.h"
76
77 #include "support/convert.h"
78 #include "support/debug.h"
79 #include "support/ExceptionMessage.h"
80 #include "support/filetools.h"
81 #include "support/gettext.h"
82 #include "support/lassert.h"
83 #include "support/lstrings.h"
84 #include "support/Package.h"
85 #include "support/types.h"
86
87 #include <cerrno>
88 #include <fstream>
89 #include <functional>
90 #include <iterator>
91 #include <sstream>
92 #include <vector>
93
94 using namespace std;
95 using namespace lyx::support;
96
97 namespace lyx {
98
99 namespace Alert = frontend::Alert;
100
101 namespace {
102
103 /// Return an inset of this class if it exists at the current cursor position
104 template <class T>
105 T * getInsetByCode(Cursor const & cur, InsetCode code)
106 {
107         DocIterator it = cur;
108         Inset * inset = it.nextInset();
109         if (inset && inset->lyxCode() == code)
110                 return static_cast<T*>(inset);
111         return 0;
112 }
113
114
115 /// Note that comparing contents can only be used for InsetCommand
116 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
117         docstring const & contents)
118 {
119         DocIterator tmpdit = dit;
120
121         while (tmpdit) {
122                 Inset const * inset = tmpdit.nextInset();
123                 if (inset) {
124                         bool const valid_code = std::find(codes.begin(), codes.end(),
125                                 inset->lyxCode()) != codes.end();
126                         InsetCommand const * ic = inset->asInsetCommand();
127                         bool const same_or_no_contents =  contents.empty()
128                                 || (ic && (ic->getFirstNonOptParam() == contents));
129
130                         if (valid_code && same_or_no_contents) {
131                                 dit = tmpdit;
132                                 return true;
133                         }
134                 }
135                 tmpdit.forwardInset();
136         }
137
138         return false;
139 }
140
141
142 /// Looks for next inset with one of the given codes.
143 /// Note that same_content can only be used for InsetCommand
144 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
145         bool same_content)
146 {
147         docstring contents;
148         DocIterator tmpdit = dit;
149         tmpdit.forwardInset();
150         if (!tmpdit)
151                 return false;
152
153         Inset const * inset = tmpdit.nextInset();
154         if (same_content && inset) {
155                 InsetCommand const * ic = inset->asInsetCommand();
156                 if (ic) {
157                         bool const valid_code = std::find(codes.begin(), codes.end(),
158                                 ic->lyxCode()) != codes.end();
159                         if (valid_code)
160                                 contents = ic->getFirstNonOptParam();
161                 }
162         }
163
164         if (!findNextInset(tmpdit, codes, contents)) {
165                 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
166                         Inset * inset = &tmpdit.bottom().inset();
167                         tmpdit = doc_iterator_begin(&inset->buffer(), inset);
168                         if (!findNextInset(tmpdit, codes, contents))
169                                 return false;
170                 } else {
171                         return false;
172                 }
173         }
174
175         dit = tmpdit;
176         return true;
177 }
178
179
180 /// Looks for next inset with the given code
181 void findInset(DocIterator & dit, InsetCode code, bool same_content)
182 {
183         findInset(dit, vector<InsetCode>(1, code), same_content);
184 }
185
186
187 /// Moves cursor to the next inset with one of the given codes.
188 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
189                bool same_content)
190 {
191         Cursor tmpcur = bv->cursor();
192         if (!findInset(tmpcur, codes, same_content)) {
193                 bv->cursor().message(_("No more insets"));
194                 return;
195         }
196
197         tmpcur.clearSelection();
198         bv->setCursor(tmpcur);
199         bv->showCursor();
200 }
201
202
203 /// Moves cursor to the next inset with given code.
204 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
205 {
206         gotoInset(bv, vector<InsetCode>(1, code), same_content);
207 }
208
209
210 /// A map from a Text to the associated text metrics
211 typedef map<Text const *, TextMetrics> TextMetricsCache;
212
213 enum ScreenUpdateStrategy {
214         NoScreenUpdate,
215         SingleParUpdate,
216         FullScreenUpdate,
217         DecorationUpdate
218 };
219
220 } // namespace
221
222
223 /////////////////////////////////////////////////////////////////////
224 //
225 // BufferView
226 //
227 /////////////////////////////////////////////////////////////////////
228
229 struct BufferView::Private
230 {
231         Private(BufferView & bv) : update_strategy_(FullScreenUpdate),
232                 update_flags_(Update::Force),
233                 wh_(0), cursor_(bv),
234                 anchor_pit_(0), anchor_ypos_(0),
235                 inlineCompletionUniqueChars_(0),
236                 last_inset_(0), clickable_inset_(false),
237                 mouse_position_cache_(),
238                 bookmark_edit_position_(-1), gui_(0),
239                 horiz_scroll_offset_(0), repaint_caret_row_(false)
240         {
241                 xsel_cache_.set = false;
242         }
243
244         ///
245         ScrollbarParameters scrollbarParameters_;
246         ///
247         ScreenUpdateStrategy update_strategy_;
248         ///
249         Update::flags update_flags_;
250         ///
251         CoordCache coord_cache_;
252
253         /// Estimated average par height for scrollbar.
254         int wh_;
255         /// this is used to handle XSelection events in the right manner.
256         struct {
257                 CursorSlice cursor;
258                 CursorSlice anchor;
259                 bool set;
260         } xsel_cache_;
261         ///
262         Cursor cursor_;
263         ///
264         pit_type anchor_pit_;
265         ///
266         int anchor_ypos_;
267         ///
268         vector<int> par_height_;
269
270         ///
271         DocIterator inlineCompletionPos_;
272         ///
273         docstring inlineCompletion_;
274         ///
275         size_t inlineCompletionUniqueChars_;
276
277         /// keyboard mapping object.
278         Intl intl_;
279
280         /// last visited inset.
281         /** kept to send setMouseHover(false).
282           * Not owned, so don't delete.
283           */
284         Inset const * last_inset_;
285         /// are we hovering something that we can click
286         bool clickable_inset_;
287
288         /// position of the mouse at the time of the last mouse move
289         /// This is used to update the hovering status of inset in
290         /// cases where the buffer is scrolled, but the mouse didn't move.
291         Point mouse_position_cache_;
292
293         // cache for id of the paragraph which was edited the last time
294         int bookmark_edit_position_;
295
296         mutable TextMetricsCache text_metrics_;
297
298         /// Whom to notify.
299         /** Not owned, so don't delete.
300           */
301         frontend::GuiBufferViewDelegate * gui_;
302
303         /// Cache for Find Next
304         FuncRequest search_request_cache_;
305
306         ///
307         map<string, Inset *> edited_insets_;
308
309         /// When the row where the cursor lies is scrolled, this
310         /// contains the scroll offset
311         int horiz_scroll_offset_;
312         /// a slice pointing to the start of the row where the cursor
313         /// is (at last draw time)
314         CursorSlice current_row_slice_;
315         /// a slice pointing to the start of the row where cursor was
316         /// at previous draw event
317         CursorSlice last_row_slice_;
318
319         /// a slice pointing to where the cursor has been drawn after the current
320         /// draw() call.
321         CursorSlice caret_slice_;
322         /// indicates whether the caret slice needs to be repainted in this draw() run.
323         bool repaint_caret_row_;
324 };
325
326
327 BufferView::BufferView(Buffer & buf)
328         : width_(0), height_(0), full_screen_(false), buffer_(buf),
329       d(new Private(*this))
330 {
331         d->xsel_cache_.set = false;
332         d->intl_.initKeyMapper(lyxrc.use_kbmap);
333
334         d->cursor_.setBuffer(&buf);
335         d->cursor_.push(buffer_.inset());
336         d->cursor_.resetAnchor();
337         d->cursor_.setCurrentFont();
338
339         buffer_.updatePreviews();
340 }
341
342
343 BufferView::~BufferView()
344 {
345         // current buffer is going to be switched-off, save cursor pos
346         // Ideally, the whole cursor stack should be saved, but session
347         // currently can only handle bottom (whole document) level pit and pos.
348         // That is to say, if a cursor is in a nested inset, it will be
349         // restore to the left of the top level inset.
350         LastFilePosSection::FilePos fp;
351         fp.pit = d->cursor_.bottom().pit();
352         fp.pos = d->cursor_.bottom().pos();
353         theSession().lastFilePos().save(buffer_.fileName(), fp);
354
355         if (d->last_inset_)
356                 d->last_inset_->setMouseHover(this, false);
357
358         delete d;
359 }
360
361
362 int BufferView::rightMargin() const
363 {
364         // The value used to be hardcoded to 10, which is 0.1in at 100dpi
365         int const default_margin = Length(0.1, Length::IN).inPixels(0);
366         // The additional test for the case the outliner is opened.
367         if (!full_screen_ || !lyxrc.full_screen_limit
368             || width_ < lyxrc.full_screen_width + 2 * default_margin)
369                 return default_margin;
370
371         return (width_ - lyxrc.full_screen_width) / 2;
372 }
373
374
375 int BufferView::leftMargin() const
376 {
377         return rightMargin();
378 }
379
380
381 int BufferView::inPixels(Length const & len) const
382 {
383         Font const font = buffer().params().getFont();
384         return len.inPixels(workWidth(), theFontMetrics(font).em());
385 }
386
387
388 bool BufferView::isTopScreen() const
389 {
390         return 0 == d->scrollbarParameters_.min;
391 }
392
393
394 bool BufferView::isBottomScreen() const
395 {
396         return 0 == d->scrollbarParameters_.max;
397 }
398
399
400 Intl & BufferView::getIntl()
401 {
402         return d->intl_;
403 }
404
405
406 Intl const & BufferView::getIntl() const
407 {
408         return d->intl_;
409 }
410
411
412 CoordCache & BufferView::coordCache()
413 {
414         return d->coord_cache_;
415 }
416
417
418 CoordCache const & BufferView::coordCache() const
419 {
420         return d->coord_cache_;
421 }
422
423
424 Buffer & BufferView::buffer()
425 {
426         return buffer_;
427 }
428
429
430 Buffer const & BufferView::buffer() const
431 {
432         return buffer_;
433 }
434
435
436 bool BufferView::needsFitCursor() const
437 {
438         if (cursorStatus(d->cursor_) == CUR_INSIDE) {
439                 frontend::FontMetrics const & fm =
440                         theFontMetrics(d->cursor_.getFont().fontInfo());
441                 int const asc = fm.maxAscent();
442                 int const des = fm.maxDescent();
443                 Point const p = getPos(d->cursor_);
444                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
445                         return false;
446         }
447         return true;
448 }
449
450
451 namespace {
452
453 // this is for debugging only.
454 string flagsAsString(Update::flags flags)
455 {
456         if (flags == Update::None)
457                 return "None ";
458         return string((flags & Update::FitCursor) ? "FitCursor " : "")
459                 + ((flags & Update::Force) ? "Force " : "")
460                 + ((flags & Update::ForceDraw) ? "ForceDraw " : "")
461                 + ((flags & Update::SinglePar) ? "SinglePar " : "");
462 }
463
464 }
465
466 void BufferView::processUpdateFlags(Update::flags flags)
467 {
468         LYXERR(Debug::PAINTING, "BufferView::processUpdateFlags( "
469                    << flagsAsString(flags) << ")  buffer: " << &buffer_);
470
471         // Case when no explicit update is requested.
472         if (flags == Update::None)
473                 return;
474
475         // SinglePar is ignored for now (this should probably change). We
476         // set it ourselves below, at the price of always rebreaking the
477         // paragraph at cursor. This can be expensive for large tables.
478         flags = flags & ~Update::SinglePar;
479
480         // First check whether the metrics and inset positions should be updated
481         if (flags & Update::Force) {
482                 // This will update the CoordCache items and replace Force
483                 // with ForceDraw in flags.
484                 updateMetrics(flags);
485         }
486
487         // Then make sure that the screen contains the cursor if needed
488         if (flags & Update::FitCursor) {
489                 if (needsFitCursor()) {
490                         scrollToCursor(d->cursor_, false);
491                         // Metrics have to be recomputed (maybe again)
492                         updateMetrics(flags);
493                 }
494                 flags = flags & ~Update::FitCursor;
495         }
496
497         // Finally detect whether we can only repaint a single paragraph
498         if (!(flags & Update::ForceDraw)) {
499                 if (singleParUpdate())
500                         flags = flags | Update::SinglePar;
501                 else
502                         updateMetrics(flags);
503         }
504
505         // Add flags to the the update flags. These will be reset to None
506         // after the redraw is actually done
507         d->update_flags_ = d->update_flags_ | flags;
508         LYXERR(Debug::PAINTING, "Cumulative flags: " << flagsAsString(flags));
509
510         // Now compute the update strategy
511         // Possibly values in flag are None, Decoration, ForceDraw
512         LATTEST((d->update_flags_ & ~(Update::None | Update::SinglePar
513                                       | Update::Decoration | Update::ForceDraw)) == 0);
514
515         if (d->update_flags_ & Update::ForceDraw)
516                 d->update_strategy_ = FullScreenUpdate;
517         else if (d->update_flags_ & Update::Decoration)
518                 d->update_strategy_ = DecorationUpdate;
519         else if (d->update_flags_ & Update::SinglePar)
520                 d->update_strategy_ = SingleParUpdate;
521         else {
522                 // no need to redraw anything.
523                 d->update_strategy_ = NoScreenUpdate;
524         }
525
526         updateHoveredInset();
527
528         // Trigger a redraw.
529         buffer_.changed(false);
530 }
531
532
533 void BufferView::updateScrollbar()
534 {
535         if (height_ == 0 && width_ == 0)
536                 return;
537
538         // We prefer fixed size line scrolling.
539         d->scrollbarParameters_.single_step = defaultRowHeight();
540         // We prefer full screen page scrolling.
541         d->scrollbarParameters_.page_step = height_;
542
543         Text & t = buffer_.text();
544         TextMetrics & tm = d->text_metrics_[&t];
545
546         LYXERR(Debug::GUI, " Updating scrollbar: height: "
547                 << t.paragraphs().size()
548                 << " curr par: " << d->cursor_.bottom().pit()
549                 << " default height " << defaultRowHeight());
550
551         size_t const parsize = t.paragraphs().size();
552         if (d->par_height_.size() != parsize) {
553                 d->par_height_.clear();
554                 // FIXME: We assume a default paragraph height of 2 rows. This
555                 // should probably be pondered with the screen width.
556                 d->par_height_.resize(parsize, defaultRowHeight() * 2);
557         }
558
559         // Look at paragraph heights on-screen
560         pair<pit_type, ParagraphMetrics const *> first = tm.first();
561         pair<pit_type, ParagraphMetrics const *> last = tm.last();
562         for (pit_type pit = first.first; pit <= last.first; ++pit) {
563                 d->par_height_[pit] = tm.parMetrics(pit).height();
564                 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
565                         << d->par_height_[pit]);
566         }
567
568         int top_pos = first.second->position() - first.second->ascent();
569         int bottom_pos = last.second->position() + last.second->descent();
570         bool first_visible = first.first == 0 && top_pos >= 0;
571         bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
572         if (first_visible && last_visible) {
573                 d->scrollbarParameters_.min = 0;
574                 d->scrollbarParameters_.max = 0;
575                 return;
576         }
577
578         d->scrollbarParameters_.min = top_pos;
579         for (size_t i = 0; i != size_t(first.first); ++i)
580                 d->scrollbarParameters_.min -= d->par_height_[i];
581         d->scrollbarParameters_.max = bottom_pos;
582         for (size_t i = last.first + 1; i != parsize; ++i)
583                 d->scrollbarParameters_.max += d->par_height_[i];
584
585         // The reference is the top position so we remove one page.
586         if (lyxrc.scroll_below_document)
587                 d->scrollbarParameters_.max -= minVisiblePart();
588         else
589                 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
590
591         // 0 must be inside the range as it denotes the current position
592         if (d->scrollbarParameters_.max < 0)
593                 d->scrollbarParameters_.max = 0;
594         if (d->scrollbarParameters_.min > 0)
595                 d->scrollbarParameters_.min = 0;
596 }
597
598
599 ScrollbarParameters const & BufferView::scrollbarParameters() const
600 {
601         return d->scrollbarParameters_;
602 }
603
604
605 docstring BufferView::toolTip(int x, int y) const
606 {
607         // Get inset under mouse, if there is one.
608         Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
609         if (!covering_inset)
610                 // No inset, no tooltip...
611                 return docstring();
612         return covering_inset->toolTip(*this, x, y);
613 }
614
615
616 string BufferView::contextMenu(int x, int y) const
617 {
618         //If there is a selection, return the containing inset menu
619         if (d->cursor_.selection())
620                 return d->cursor_.inset().contextMenu(*this, x, y);
621
622         // Get inset under mouse, if there is one.
623         Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
624         if (covering_inset)
625                 return covering_inset->contextMenu(*this, x, y);
626
627         return buffer_.inset().contextMenu(*this, x, y);
628 }
629
630
631
632 void BufferView::scrollDocView(int const value, bool update)
633 {
634         // The scrollbar values are relative to the top of the screen, therefore the
635         // offset is equal to the target value.
636
637         // No scrolling at all? No need to redraw anything
638         if (value == 0)
639                 return;
640
641         // If the offset is less than 2 screen height, prefer to scroll instead.
642         if (abs(value) <= 2 * height_) {
643                 d->anchor_ypos_ -= value;
644                 processUpdateFlags(Update::Force);
645                 return;
646         }
647
648         // cut off at the top
649         if (value <= d->scrollbarParameters_.min) {
650                 DocIterator dit = doc_iterator_begin(&buffer_);
651                 showCursor(dit, false, update);
652                 LYXERR(Debug::SCROLLING, "scroll to top");
653                 return;
654         }
655
656         // cut off at the bottom
657         if (value >= d->scrollbarParameters_.max) {
658                 DocIterator dit = doc_iterator_end(&buffer_);
659                 dit.backwardPos();
660                 showCursor(dit, false, update);
661                 LYXERR(Debug::SCROLLING, "scroll to bottom");
662                 return;
663         }
664
665         // find paragraph at target position
666         int par_pos = d->scrollbarParameters_.min;
667         pit_type i = 0;
668         for (; i != int(d->par_height_.size()); ++i) {
669                 par_pos += d->par_height_[i];
670                 if (par_pos >= value)
671                         break;
672         }
673
674         if (par_pos < value) {
675                 // It seems we didn't find the correct pit so stay on the safe side and
676                 // scroll to bottom.
677                 LYXERR0("scrolling position not found!");
678                 scrollDocView(d->scrollbarParameters_.max, update);
679                 return;
680         }
681
682         DocIterator dit = doc_iterator_begin(&buffer_);
683         dit.pit() = i;
684         LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
685         showCursor(dit, false, update);
686 }
687
688
689 // FIXME: this method is not working well.
690 void BufferView::setCursorFromScrollbar()
691 {
692         TextMetrics & tm = d->text_metrics_[&buffer_.text()];
693
694         int const height = 2 * defaultRowHeight();
695         int const first = height;
696         int const last = height_ - height;
697         int newy = 0;
698         Cursor const & oldcur = d->cursor_;
699
700         switch (cursorStatus(oldcur)) {
701         case CUR_ABOVE:
702                 newy = first;
703                 break;
704         case CUR_BELOW:
705                 newy = last;
706                 break;
707         case CUR_INSIDE:
708                 int const y = getPos(oldcur).y_;
709                 newy = min(last, max(y, first));
710                 if (y == newy)
711                         return;
712         }
713         // We reset the cursor because cursorStatus() does not
714         // work when the cursor is within mathed.
715         Cursor cur(*this);
716         cur.reset();
717         tm.setCursorFromCoordinates(cur, 0, newy);
718
719         // update the bufferview cursor and notify insets
720         // FIXME: Care about the d->cursor_ flags to redraw if needed
721         Cursor old = d->cursor_;
722         mouseSetCursor(cur);
723         // the DEPM call in mouseSetCursor() might have destroyed the
724         // paragraph the cursor is in.
725         bool badcursor = old.fixIfBroken();
726         badcursor |= notifyCursorLeavesOrEnters(old, d->cursor_);
727         if (badcursor)
728                 d->cursor_.fixIfBroken();
729 }
730
731
732 Change const BufferView::getCurrentChange() const
733 {
734         if (!d->cursor_.selection())
735                 return Change(Change::UNCHANGED);
736
737         DocIterator dit = d->cursor_.selectionBegin();
738         // The selected content might have been changed (see #7685)
739         dit = dit.getInnerText();
740         return dit.paragraph().lookupChange(dit.pos());
741 }
742
743
744 // this could be used elsewhere as well?
745 // FIXME: This does not work within mathed!
746 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
747 {
748         Point const p = getPos(dit);
749         if (p.y_ < 0)
750                 return CUR_ABOVE;
751         if (p.y_ > workHeight())
752                 return CUR_BELOW;
753         return CUR_INSIDE;
754 }
755
756
757 void BufferView::bookmarkEditPosition()
758 {
759         // Don't eat cpu time for each keystroke
760         if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
761                 return;
762         saveBookmark(0);
763         d->bookmark_edit_position_ = d->cursor_.paragraph().id();
764 }
765
766
767 void BufferView::saveBookmark(unsigned int idx)
768 {
769         // tentatively save bookmark, id and pos will be used to
770         // acturately locate a bookmark in a 'live' lyx session.
771         // pit and pos will be updated with bottom level pit/pos
772         // when lyx exits.
773         if (!buffer_.isInternal()) {
774                 theSession().bookmarks().save(
775                         buffer_.fileName(),
776                         d->cursor_.bottom().pit(),
777                         d->cursor_.bottom().pos(),
778                         d->cursor_.paragraph().id(),
779                         d->cursor_.pos(),
780                         idx
781                         );
782                 if (idx)
783                         // emit message signal.
784                         message(_("Save bookmark"));
785         }
786 }
787
788
789 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
790         int top_id, pos_type top_pos)
791 {
792         bool success = false;
793         DocIterator dit;
794
795         d->cursor_.clearSelection();
796
797         // if a valid par_id is given, try it first
798         // This is the case for a 'live' bookmark when unique paragraph ID
799         // is used to track bookmarks.
800         if (top_id > 0) {
801                 dit = buffer_.getParFromID(top_id);
802                 if (!dit.atEnd()) {
803                         dit.pos() = min(dit.paragraph().size(), top_pos);
804                         // Some slices of the iterator may not be
805                         // reachable (e.g. closed collapsible inset)
806                         // so the dociterator may need to be
807                         // shortened. Otherwise, setCursor may crash
808                         // lyx when the cursor can not be set to these
809                         // insets.
810                         size_t const n = dit.depth();
811                         for (size_t i = 0; i < n; ++i)
812                                 if (!dit[i].inset().editable()) {
813                                         dit.resize(i);
814                                         break;
815                                 }
816                         success = true;
817                 }
818         }
819
820         // if top_id == 0, or searching through top_id failed
821         // This is the case for a 'restored' bookmark when only bottom
822         // (document level) pit was saved. Because of this, bookmark
823         // restoration is inaccurate. If a bookmark was within an inset,
824         // it will be restored to the left of the outmost inset that contains
825         // the bookmark.
826         if (bottom_pit < int(buffer_.paragraphs().size())) {
827                 dit = doc_iterator_begin(&buffer_);
828
829                 dit.pit() = bottom_pit;
830                 dit.pos() = min(bottom_pos, dit.paragraph().size());
831                 success = true;
832         }
833
834         if (success) {
835                 // Note: only bottom (document) level pit is set.
836                 setCursor(dit);
837                 // set the current font.
838                 d->cursor_.setCurrentFont();
839                 // Do not forget to reset the anchor (see #9912)
840                 d->cursor_.resetAnchor();
841                 processUpdateFlags(Update::FitCursor);
842         }
843
844         return success;
845 }
846
847
848 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
849 {
850         if (d->cursor_.real_current_font.isRightToLeft()) {
851                 if (d->intl_.keymap == Intl::PRIMARY)
852                         d->intl_.keyMapSec();
853         } else {
854                 if (d->intl_.keymap == Intl::SECONDARY)
855                         d->intl_.keyMapPrim();
856         }
857
858         d->intl_.getTransManager().translateAndInsert(c, t, cur);
859 }
860
861
862 int BufferView::workWidth() const
863 {
864         return width_;
865 }
866
867
868 void BufferView::recenter()
869 {
870         showCursor(d->cursor_, true, true);
871 }
872
873
874 void BufferView::showCursor()
875 {
876         showCursor(d->cursor_, false, true);
877 }
878
879
880 void BufferView::showCursor(DocIterator const & dit,
881         bool recenter, bool update)
882 {
883         if (scrollToCursor(dit, recenter) && update)
884                 processUpdateFlags(Update::Force);
885 }
886
887
888 void BufferView::scrollToCursor()
889 {
890         if (scrollToCursor(d->cursor_, false))
891                 processUpdateFlags(Update::Force);
892 }
893
894
895 bool BufferView::scrollToCursor(DocIterator const & dit, bool const recenter)
896 {
897         // We are not properly started yet, delay until resizing is
898         // done.
899         if (height_ == 0)
900                 return false;
901
902         LYXERR(Debug::SCROLLING, "recentering!");
903
904         CursorSlice const & bot = dit.bottom();
905         TextMetrics & tm = d->text_metrics_[bot.text()];
906
907         pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
908         int bot_pit = bot.pit();
909         if (bot_pit > max_pit) {
910                 // FIXME: Why does this happen?
911                 LYXERR0("bottom pit is greater that max pit: "
912                         << bot_pit << " > " << max_pit);
913                 bot_pit = max_pit;
914         }
915
916         if (bot_pit == tm.first().first - 1)
917                 tm.newParMetricsUp();
918         else if (bot_pit == tm.last().first + 1)
919                 tm.newParMetricsDown();
920
921         if (tm.contains(bot_pit)) {
922                 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
923                 LBUFERR(!pm.rows().empty());
924                 // FIXME: smooth scrolling doesn't work in mathed.
925                 CursorSlice const & cs = dit.innerTextSlice();
926                 int offset = coordOffset(dit).y_;
927                 int ypos = pm.position() + offset;
928                 Dimension const & row_dim =
929                         pm.getRow(cs.pos(), dit.boundary()).dimension();
930                 int scrolled = 0;
931                 if (recenter)
932                         scrolled = scroll(ypos - height_/2);
933
934                 // We try to visualize the whole row, if the row height is larger than
935                 // the screen height, we scroll to a heuristic value of height_ / 4.
936                 // FIXME: This heuristic value should be replaced by a recursive search
937                 // for a row in the inset that can be visualized completely.
938                 else if (row_dim.height() > height_) {
939                         if (ypos < defaultRowHeight())
940                                 scrolled = scroll(ypos - height_ / 4);
941                         else if (ypos > height_ - defaultRowHeight())
942                                 scrolled = scroll(ypos - 3 * height_ / 4);
943                 }
944
945                 // If the top part of the row falls of the screen, we scroll
946                 // up to align the top of the row with the top of the screen.
947                 else if (ypos - row_dim.ascent() < 0 && ypos < height_) {
948                         int ynew = row_dim.ascent();
949                         scrolled = scrollUp(ynew - ypos);
950                 }
951
952                 // If the bottom of the row falls of the screen, we scroll down.
953                 else if (ypos + row_dim.descent() > height_ && ypos > 0) {
954                         int ynew = height_ - row_dim.descent();
955                         scrolled = scrollDown(ypos - ynew);
956                 }
957
958                 // else, nothing to do, the cursor is already visible so we just return.
959                 return scrolled != 0;
960         }
961
962         // fix inline completion position
963         if (d->inlineCompletionPos_.fixIfBroken())
964                 d->inlineCompletionPos_ = DocIterator();
965
966         tm.redoParagraph(bot_pit);
967         ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
968         int offset = coordOffset(dit).y_;
969
970         d->anchor_pit_ = bot_pit;
971         CursorSlice const & cs = dit.innerTextSlice();
972         Dimension const & row_dim =
973                 pm.getRow(cs.pos(), dit.boundary()).dimension();
974
975         if (recenter)
976                 d->anchor_ypos_ = height_/2;
977         else if (d->anchor_pit_ == 0)
978                 d->anchor_ypos_ = offset + pm.ascent();
979         else if (d->anchor_pit_ == max_pit)
980                 d->anchor_ypos_ = height_ - offset - row_dim.descent();
981         else if (offset > height_)
982                 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
983         else
984                 d->anchor_ypos_ = defaultRowHeight() * 2;
985
986         return true;
987 }
988
989
990 void BufferView::makeDocumentClass()
991 {
992         DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
993         buffer_.params().makeDocumentClass();
994         updateDocumentClass(olddc);
995 }
996
997
998 void BufferView::updateDocumentClass(DocumentClassConstPtr olddc)
999 {
1000         message(_("Converting document to new document class..."));
1001
1002         StableDocIterator backcur(d->cursor_);
1003         ErrorList & el = buffer_.errorList("Class Switch");
1004         cap::switchBetweenClasses(
1005                         olddc, buffer_.params().documentClassPtr(),
1006                         static_cast<InsetText &>(buffer_.inset()), el);
1007
1008         setCursor(backcur.asDocIterator(&buffer_));
1009
1010         buffer_.errors("Class Switch");
1011 }
1012
1013
1014 /** Return the change status at cursor position, taking into account the
1015  * status at each level of the document iterator (a table in a deleted
1016  * footnote is deleted).
1017  * When \param outer is true, the top slice is not looked at.
1018  */
1019 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
1020 {
1021         size_t const depth = dit.depth() - (outer ? 1 : 0);
1022
1023         for (size_t i = 0 ; i < depth ; ++i) {
1024                 CursorSlice const & slice = dit[i];
1025                 if (!slice.inset().inMathed()
1026                     && slice.pos() < slice.paragraph().size()) {
1027                         Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
1028                         if (ch != Change::UNCHANGED)
1029                                 return ch;
1030                 }
1031         }
1032         return Change::UNCHANGED;
1033 }
1034
1035
1036 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1037 {
1038         FuncCode const act = cmd.action();
1039
1040         // Can we use a readonly buffer?
1041         if (buffer_.isReadonly()
1042             && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1043             && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1044                 if (buffer_.hasReadonlyFlag())
1045                         flag.message(from_utf8(N_("Document is read-only")));
1046                 else
1047                         flag.message(from_utf8(N_("Document has been modified externally")));
1048                 flag.setEnabled(false);
1049                 return true;
1050         }
1051
1052         // Are we in a DELETED change-tracking region?
1053         if (lookupChangeType(d->cursor_, true) == Change::DELETED
1054             && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1055             && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1056                 flag.message(from_utf8(N_("This portion of the document is deleted.")));
1057                 flag.setEnabled(false);
1058                 return true;
1059         }
1060
1061         Cursor & cur = d->cursor_;
1062
1063         if (cur.getStatus(cmd, flag))
1064                 return true;
1065
1066         switch (act) {
1067
1068         // FIXME: This is a bit problematic because we don't check if this is
1069         // a document BufferView or not for these LFUNs. We probably have to
1070         // dispatch both to currentBufferView() and, if that fails,
1071         // to documentBufferView(); same as we do now for current Buffer and
1072         // document Buffer. Ideally those LFUN should go to Buffer as they
1073         // operate on the full Buffer and the cursor is only needed either for
1074         // an Undo record or to restore a cursor position. But we don't know
1075         // how to do that inside Buffer of course.
1076         case LFUN_BUFFER_PARAMS_APPLY:
1077         case LFUN_LAYOUT_MODULES_CLEAR:
1078         case LFUN_LAYOUT_MODULE_ADD:
1079         case LFUN_LAYOUT_RELOAD:
1080         case LFUN_TEXTCLASS_APPLY:
1081         case LFUN_TEXTCLASS_LOAD:
1082                 flag.setEnabled(!buffer_.isReadonly());
1083                 break;
1084
1085         case LFUN_UNDO:
1086                 // We do not use the LyXAction flag for readonly because Undo sets the
1087                 // buffer clean/dirty status by itself.
1088                 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasUndoStack());
1089                 break;
1090         case LFUN_REDO:
1091                 // We do not use the LyXAction flag for readonly because Redo sets the
1092                 // buffer clean/dirty status by itself.
1093                 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasRedoStack());
1094                 break;
1095         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1096         case LFUN_FILE_INSERT_PLAINTEXT: {
1097                 docstring const fname = cmd.argument();
1098                 if (!FileName::isAbsolute(to_utf8(fname))) {
1099                         flag.message(_("Absolute filename expected."));
1100                         return false;
1101                 }
1102                 flag.setEnabled(cur.inTexted());
1103                 break;
1104         }
1105         case LFUN_FILE_INSERT:
1106         case LFUN_BOOKMARK_SAVE:
1107                 // FIXME: Actually, these LFUNS should be moved to Text
1108                 flag.setEnabled(cur.inTexted());
1109                 break;
1110
1111         case LFUN_FONT_STATE:
1112         case LFUN_LABEL_INSERT:
1113         case LFUN_INFO_INSERT:
1114         case LFUN_PARAGRAPH_GOTO:
1115         case LFUN_NOTE_NEXT:
1116         case LFUN_REFERENCE_NEXT:
1117         case LFUN_WORD_FIND:
1118         case LFUN_WORD_FIND_FORWARD:
1119         case LFUN_WORD_FIND_BACKWARD:
1120         case LFUN_WORD_REPLACE:
1121         case LFUN_MARK_OFF:
1122         case LFUN_MARK_ON:
1123         case LFUN_MARK_TOGGLE:
1124         case LFUN_SCREEN_RECENTER:
1125         case LFUN_SCREEN_SHOW_CURSOR:
1126         case LFUN_BIBTEX_DATABASE_ADD:
1127         case LFUN_BIBTEX_DATABASE_DEL:
1128         case LFUN_STATISTICS:
1129         case LFUN_KEYMAP_OFF:
1130         case LFUN_KEYMAP_PRIMARY:
1131         case LFUN_KEYMAP_SECONDARY:
1132         case LFUN_KEYMAP_TOGGLE:
1133         case LFUN_INSET_SELECT_ALL:
1134                 flag.setEnabled(true);
1135                 break;
1136
1137         case LFUN_GRAPHICS_UNIFY:
1138                 flag.setEnabled(cur.selection());
1139                 break;
1140
1141         case LFUN_WORD_FINDADV: {
1142                 FindAndReplaceOptions opt;
1143                 istringstream iss(to_utf8(cmd.argument()));
1144                 iss >> opt;
1145                 flag.setEnabled(opt.repl_buf_name.empty()
1146                                 || !buffer_.isReadonly());
1147                 break;
1148         }
1149
1150         case LFUN_LABEL_GOTO:
1151                 flag.setEnabled(!cmd.argument().empty()
1152                     || getInsetByCode<InsetRef>(cur, REF_CODE));
1153                 break;
1154
1155         case LFUN_CHANGES_MERGE:
1156         case LFUN_CHANGE_NEXT:
1157         case LFUN_CHANGE_PREVIOUS:
1158         case LFUN_ALL_CHANGES_ACCEPT:
1159         case LFUN_ALL_CHANGES_REJECT:
1160                 flag.setEnabled(buffer_.areChangesPresent());
1161                 break;
1162
1163         case LFUN_SCREEN_UP:
1164         case LFUN_SCREEN_DOWN:
1165         case LFUN_SCROLL:
1166         case LFUN_SCREEN_UP_SELECT:
1167         case LFUN_SCREEN_DOWN_SELECT:
1168         case LFUN_INSET_FORALL:
1169                 flag.setEnabled(true);
1170                 break;
1171
1172         case LFUN_LAYOUT_TABULAR:
1173                 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1174                 break;
1175
1176         case LFUN_LAYOUT:
1177                 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1178                 break;
1179
1180         case LFUN_LAYOUT_PARAGRAPH:
1181                 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1182                 break;
1183
1184         case LFUN_BRANCH_ADD_INSERT:
1185                 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1186                 break;
1187
1188         case LFUN_DIALOG_SHOW_NEW_INSET:
1189                 // FIXME: this is wrong, but I do not understand the
1190                 // intent (JMarc)
1191                 if (cur.inset().lyxCode() == CAPTION_CODE)
1192                         return cur.inset().getStatus(cur, cmd, flag);
1193                 // FIXME we should consider passthru paragraphs too.
1194                 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1195                 break;
1196
1197         case LFUN_CITATION_INSERT: {
1198                 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1199                 // FIXME: This could turn in a recursive hell.
1200                 // Shouldn't we use Buffer::getStatus() instead?
1201                 flag.setEnabled(lyx::getStatus(fr).enabled());
1202                 break;
1203         }
1204         case LFUN_INSET_APPLY: {
1205                 string const name = cmd.getArg(0);
1206                 Inset * inset = editedInset(name);
1207                 if (inset) {
1208                         FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1209                         if (!inset->getStatus(cur, fr, flag)) {
1210                                 // Every inset is supposed to handle this
1211                                 LASSERT(false, break);
1212                         }
1213                 } else {
1214                         FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1215                         flag = lyx::getStatus(fr);
1216                 }
1217                 break;
1218         }
1219
1220         default:
1221                 return false;
1222         }
1223
1224         return true;
1225 }
1226
1227
1228 Inset * BufferView::editedInset(string const & name) const
1229 {
1230         map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1231         return it == d->edited_insets_.end() ? 0 : it->second;
1232 }
1233
1234
1235 void BufferView::editInset(string const & name, Inset * inset)
1236 {
1237         d->edited_insets_[name] = inset;
1238 }
1239
1240
1241 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1242 {
1243         LYXERR(Debug::ACTION, "BufferView::dispatch: cmd: " << cmd);
1244
1245         string const argument = to_utf8(cmd.argument());
1246         Cursor & cur = d->cursor_;
1247         Cursor old = cur;
1248
1249         // Don't dispatch function that does not apply to internal buffers.
1250         if (buffer_.isInternal()
1251             && lyxaction.funcHasFlag(cmd.action(), LyXAction::NoInternal))
1252                 return;
1253
1254         // We'll set this back to false if need be.
1255         bool dispatched = true;
1256         buffer_.undo().beginUndoGroup();
1257
1258         FuncCode const act = cmd.action();
1259         switch (act) {
1260
1261         case LFUN_BUFFER_PARAMS_APPLY: {
1262                 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
1263                 cur.recordUndoBufferParams();
1264                 istringstream ss(to_utf8(cmd.argument()));
1265                 Lexer lex;
1266                 lex.setStream(ss);
1267                 int const unknown_tokens = buffer_.readHeader(lex);
1268                 if (unknown_tokens != 0) {
1269                         LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1270                                                 << unknown_tokens << " unknown token"
1271                                                 << (unknown_tokens == 1 ? "" : "s"));
1272                 }
1273                 updateDocumentClass(olddc);
1274
1275                 // We are most certainly here because of a change in the document
1276                 // It is then better to make sure that all dialogs are in sync with
1277                 // current document settings.
1278                 dr.screenUpdate(Update::Force | Update::FitCursor);
1279                 dr.forceBufferUpdate();
1280                 break;
1281         }
1282
1283         case LFUN_LAYOUT_MODULES_CLEAR: {
1284                 // FIXME: this modifies the document in cap::switchBetweenClasses
1285                 //  without calling recordUndo. Fix this before using
1286                 //  recordUndoBufferParams().
1287                 cur.recordUndoFullBuffer();
1288                 buffer_.params().clearLayoutModules();
1289                 makeDocumentClass();
1290                 dr.screenUpdate(Update::Force);
1291                 dr.forceBufferUpdate();
1292                 break;
1293         }
1294
1295         case LFUN_LAYOUT_MODULE_ADD: {
1296                 BufferParams const & params = buffer_.params();
1297                 if (!params.layoutModuleCanBeAdded(argument)) {
1298                         LYXERR0("Module `" << argument <<
1299                                 "' cannot be added due to failed requirements or "
1300                                 "conflicts with installed modules.");
1301                         break;
1302                 }
1303                 // FIXME: this modifies the document in cap::switchBetweenClasses
1304                 //  without calling recordUndo. Fix this before using
1305                 //  recordUndoBufferParams().
1306                 cur.recordUndoFullBuffer();
1307                 buffer_.params().addLayoutModule(argument);
1308                 makeDocumentClass();
1309                 dr.screenUpdate(Update::Force);
1310                 dr.forceBufferUpdate();
1311                 break;
1312         }
1313
1314         case LFUN_TEXTCLASS_APPLY: {
1315                 // since this shortcircuits, the second call is made only if
1316                 // the first fails
1317                 bool const success =
1318                         LayoutFileList::get().load(argument, buffer_.temppath()) ||
1319                         LayoutFileList::get().load(argument, buffer_.filePath());
1320                 if (!success) {
1321                         docstring s = bformat(_("The document class `%1$s' "
1322                                                  "could not be loaded."), from_utf8(argument));
1323                         frontend::Alert::error(_("Could not load class"), s);
1324                         break;
1325                 }
1326
1327                 LayoutFile const * old_layout = buffer_.params().baseClass();
1328                 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1329
1330                 if (old_layout == new_layout)
1331                         // nothing to do
1332                         break;
1333
1334                 // Save the old, possibly modular, layout for use in conversion.
1335                 // FIXME: this modifies the document in cap::switchBetweenClasses
1336                 //  without calling recordUndo. Fix this before using
1337                 //  recordUndoBufferParams().
1338                 cur.recordUndoFullBuffer();
1339                 buffer_.params().setBaseClass(argument);
1340                 makeDocumentClass();
1341                 dr.screenUpdate(Update::Force);
1342                 dr.forceBufferUpdate();
1343                 break;
1344         }
1345
1346         case LFUN_TEXTCLASS_LOAD: {
1347                 // since this shortcircuits, the second call is made only if
1348                 // the first fails
1349                 bool const success =
1350                         LayoutFileList::get().load(argument, buffer_.temppath()) ||
1351                         LayoutFileList::get().load(argument, buffer_.filePath());
1352                 if (!success) {
1353                         docstring s = bformat(_("The document class `%1$s' "
1354                                                  "could not be loaded."), from_utf8(argument));
1355                         frontend::Alert::error(_("Could not load class"), s);
1356                 }
1357                 break;
1358         }
1359
1360         case LFUN_LAYOUT_RELOAD: {
1361                 LayoutFileIndex bc = buffer_.params().baseClassID();
1362                 LayoutFileList::get().reset(bc);
1363                 buffer_.params().setBaseClass(bc);
1364                 makeDocumentClass();
1365                 dr.screenUpdate(Update::Force);
1366                 dr.forceBufferUpdate();
1367                 break;
1368         }
1369
1370         case LFUN_UNDO:
1371                 dr.setMessage(_("Undo"));
1372                 cur.clearSelection();
1373                 if (!cur.textUndo())
1374                         dr.setMessage(_("No further undo information"));
1375                 else
1376                         dr.screenUpdate(Update::Force | Update::FitCursor);
1377                 dr.forceBufferUpdate();
1378                 break;
1379
1380         case LFUN_REDO:
1381                 dr.setMessage(_("Redo"));
1382                 cur.clearSelection();
1383                 if (!cur.textRedo())
1384                         dr.setMessage(_("No further redo information"));
1385                 else
1386                         dr.screenUpdate(Update::Force | Update::FitCursor);
1387                 dr.forceBufferUpdate();
1388                 break;
1389
1390         case LFUN_FONT_STATE:
1391                 dr.setMessage(cur.currentState(false));
1392                 break;
1393
1394         case LFUN_BOOKMARK_SAVE:
1395                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1396                 break;
1397
1398         case LFUN_LABEL_GOTO: {
1399                 docstring label = cmd.argument();
1400                 if (label.empty()) {
1401                         InsetRef * inset =
1402                                 getInsetByCode<InsetRef>(cur, REF_CODE);
1403                         if (inset) {
1404                                 label = inset->getParam("reference");
1405                                 // persistent=false: use temp_bookmark
1406                                 saveBookmark(0);
1407                         }
1408                 }
1409                 if (!label.empty()) {
1410                         gotoLabel(label);
1411                         // at the moment, this is redundant, since gotoLabel will
1412                         // eventually call LFUN_PARAGRAPH_GOTO, but it seems best
1413                         // to have it here.
1414                         dr.screenUpdate(Update::Force | Update::FitCursor);
1415                 }
1416                 break;
1417         }
1418
1419         case LFUN_PARAGRAPH_GOTO: {
1420                 int const id = convert<int>(cmd.getArg(0));
1421                 pos_type const pos = convert<int>(cmd.getArg(1));
1422                 if (id < 0)
1423                         break;
1424                 string const str_id_end = cmd.getArg(2);
1425                 string const str_pos_end = cmd.getArg(3);
1426                 int i = 0;
1427                 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1428                         b = theBufferList().next(b)) {
1429
1430                         Cursor cur(*this);
1431                         cur.setCursor(b->getParFromID(id));
1432                         if (cur.atEnd()) {
1433                                 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1434                                 ++i;
1435                                 continue;
1436                         }
1437                         LYXERR(Debug::INFO, "Paragraph " << cur.paragraph().id()
1438                                 << " found in buffer `"
1439                                 << b->absFileName() << "'.");
1440
1441                         if (b == &buffer_) {
1442                                 bool success;
1443                                 if (str_id_end.empty() || str_pos_end.empty()) {
1444                                         // Set the cursor
1445                                         cur.pos() = pos;
1446                                         mouseSetCursor(cur);
1447                                         success = true;
1448                                 } else {
1449                                         int const id_end = convert<int>(str_id_end);
1450                                         pos_type const pos_end = convert<int>(str_pos_end);
1451                                         success = setCursorFromEntries({id, pos},
1452                                                                        {id_end, pos_end});
1453                                 }
1454                                 if (success)
1455                                         dr.screenUpdate(Update::Force | Update::FitCursor);
1456                         } else {
1457                                 // Switch to other buffer view and resend cmd
1458                                 lyx::dispatch(FuncRequest(
1459                                         LFUN_BUFFER_SWITCH, b->absFileName()));
1460                                 lyx::dispatch(cmd);
1461                         }
1462                         break;
1463                 }
1464                 break;
1465         }
1466
1467         case LFUN_NOTE_NEXT:
1468                 gotoInset(this, NOTE_CODE, false);
1469                 break;
1470
1471         case LFUN_REFERENCE_NEXT: {
1472                 vector<InsetCode> tmp;
1473                 tmp.push_back(LABEL_CODE);
1474                 tmp.push_back(REF_CODE);
1475                 gotoInset(this, tmp, true);
1476                 break;
1477         }
1478
1479         case LFUN_CHANGE_NEXT:
1480                 findNextChange(this);
1481                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1482                 dr.screenUpdate(Update::Force | Update::FitCursor);
1483                 break;
1484
1485         case LFUN_CHANGE_PREVIOUS:
1486                 findPreviousChange(this);
1487                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1488                 dr.screenUpdate(Update::Force | Update::FitCursor);
1489                 break;
1490
1491         case LFUN_CHANGES_MERGE:
1492                 if (findNextChange(this) || findPreviousChange(this)) {
1493                         dr.screenUpdate(Update::Force | Update::FitCursor);
1494                         dr.forceBufferUpdate();
1495                         showDialog("changes");
1496                 }
1497                 break;
1498
1499         case LFUN_ALL_CHANGES_ACCEPT:
1500                 // select complete document
1501                 cur.reset();
1502                 cur.selHandle(true);
1503                 buffer_.text().cursorBottom(cur);
1504                 // accept everything in a single step to support atomic undo
1505                 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1506                 cur.resetAnchor();
1507                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1508                 dr.screenUpdate(Update::Force | Update::FitCursor);
1509                 dr.forceBufferUpdate();
1510                 break;
1511
1512         case LFUN_ALL_CHANGES_REJECT:
1513                 // select complete document
1514                 cur.reset();
1515                 cur.selHandle(true);
1516                 buffer_.text().cursorBottom(cur);
1517                 // reject everything in a single step to support atomic undo
1518                 // Note: reject does not work recursively; the user may have to repeat the operation
1519                 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1520                 cur.resetAnchor();
1521                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1522                 dr.screenUpdate(Update::Force | Update::FitCursor);
1523                 dr.forceBufferUpdate();
1524                 break;
1525
1526         case LFUN_WORD_FIND_FORWARD:
1527         case LFUN_WORD_FIND_BACKWARD: {
1528                 // FIXME THREAD
1529                 // Would it maybe be better if this variable were view specific anyway?
1530                 static docstring last_search;
1531                 docstring searched_string;
1532
1533                 if (!cmd.argument().empty()) {
1534                         last_search = cmd.argument();
1535                         searched_string = cmd.argument();
1536                 } else {
1537                         searched_string = last_search;
1538                 }
1539
1540                 if (searched_string.empty())
1541                         break;
1542
1543                 bool const fw = act == LFUN_WORD_FIND_FORWARD;
1544                 docstring const data =
1545                         find2string(searched_string, true, false, fw);
1546                 bool found = lyxfind(this, FuncRequest(LFUN_WORD_FIND, data));
1547                 if (found)
1548                         dr.screenUpdate(Update::Force | Update::FitCursor);
1549                 break;
1550         }
1551
1552         case LFUN_WORD_FIND: {
1553                 FuncRequest req = cmd;
1554                 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1555                         req = d->search_request_cache_;
1556                 if (req.argument().empty()) {
1557                         lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1558                         break;
1559                 }
1560                 if (lyxfind(this, req))
1561                         dr.screenUpdate(Update::Force | Update::FitCursor);
1562
1563                 d->search_request_cache_ = req;
1564                 break;
1565         }
1566
1567         case LFUN_WORD_REPLACE: {
1568                 bool has_deleted = false;
1569                 if (cur.selection()) {
1570                         DocIterator beg = cur.selectionBegin();
1571                         DocIterator end = cur.selectionEnd();
1572                         if (beg.pit() == end.pit()) {
1573                                 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1574                                         if (!cur.inMathed() && cur.paragraph().isDeleted(p)) {
1575                                                 has_deleted = true;
1576                                                 break;
1577                                         }
1578                                 }
1579                         }
1580                 }
1581                 if (lyxreplace(this, cmd, has_deleted)) {
1582                         dr.forceBufferUpdate();
1583                         dr.screenUpdate(Update::Force | Update::FitCursor);
1584                 }
1585                 break;
1586         }
1587
1588         case LFUN_WORD_FINDADV: {
1589                 FindAndReplaceOptions opt;
1590                 istringstream iss(to_utf8(cmd.argument()));
1591                 iss >> opt;
1592                 if (findAdv(this, opt)) {
1593                         dr.screenUpdate(Update::Force | Update::FitCursor);
1594                         cur.dispatched();
1595                         dispatched = true;
1596                 } else {
1597                         cur.undispatched();
1598                         dispatched = false;
1599                 }
1600                 break;
1601         }
1602
1603         case LFUN_MARK_OFF:
1604                 cur.clearSelection();
1605                 dr.setMessage(from_utf8(N_("Mark off")));
1606                 break;
1607
1608         case LFUN_MARK_ON:
1609                 cur.clearSelection();
1610                 cur.setMark(true);
1611                 dr.setMessage(from_utf8(N_("Mark on")));
1612                 break;
1613
1614         case LFUN_MARK_TOGGLE:
1615                 cur.selection(false);
1616                 if (cur.mark()) {
1617                         cur.setMark(false);
1618                         dr.setMessage(from_utf8(N_("Mark removed")));
1619                 } else {
1620                         cur.setMark(true);
1621                         dr.setMessage(from_utf8(N_("Mark set")));
1622                 }
1623                 cur.resetAnchor();
1624                 break;
1625
1626         case LFUN_SCREEN_SHOW_CURSOR:
1627                 showCursor();
1628                 break;
1629
1630         case LFUN_SCREEN_RECENTER:
1631                 recenter();
1632                 break;
1633
1634         case LFUN_BIBTEX_DATABASE_ADD: {
1635                 Cursor tmpcur = cur;
1636                 findInset(tmpcur, BIBTEX_CODE, false);
1637                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1638                                                 BIBTEX_CODE);
1639                 if (inset) {
1640                         if (inset->addDatabase(cmd.argument())) {
1641                                 buffer_.invalidateBibfileCache();
1642                                 dr.forceBufferUpdate();
1643                         }
1644                 }
1645                 break;
1646         }
1647
1648         case LFUN_BIBTEX_DATABASE_DEL: {
1649                 Cursor tmpcur = cur;
1650                 findInset(tmpcur, BIBTEX_CODE, false);
1651                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1652                                                 BIBTEX_CODE);
1653                 if (inset) {
1654                         if (inset->delDatabase(cmd.argument())) {
1655                                 buffer_.invalidateBibfileCache();
1656                                 dr.forceBufferUpdate();
1657                         }
1658                 }
1659                 break;
1660         }
1661
1662         case LFUN_GRAPHICS_UNIFY: {
1663
1664                 cur.recordUndoFullBuffer();
1665
1666                 DocIterator from, to;
1667                 from = cur.selectionBegin();
1668                 to = cur.selectionEnd();
1669
1670                 string newId = cmd.getArg(0);
1671                 bool fetchId=newId.empty(); //if we wait for groupId from first graphics inset
1672
1673                 InsetGraphicsParams grp_par;
1674                 InsetGraphics::string2params(graphics::getGroupParams(buffer_, newId), buffer_, grp_par);
1675
1676                 if (!from.nextInset())  //move to closest inset
1677                         from.forwardInset();
1678
1679                 while (!from.empty() && from < to) {
1680                         Inset * inset = from.nextInset();
1681                         if (!inset)
1682                                 break;
1683                         if (inset->lyxCode() == GRAPHICS_CODE) {
1684                                 InsetGraphics * ig = inset->asInsetGraphics();
1685                                 if (!ig)
1686                                         break;
1687                                 InsetGraphicsParams inspar = ig->getParams();
1688                                 if (fetchId) {
1689                                         grp_par = inspar;
1690                                         fetchId = false;
1691
1692                                 } else {
1693                                         grp_par.filename = inspar.filename;
1694                                         ig->setParams(grp_par);
1695                                 }
1696                         }
1697                         from.forwardInset();
1698                 }
1699                 dr.screenUpdate(Update::Force); //needed if triggered from context menu
1700                 break;
1701         }
1702
1703         case LFUN_STATISTICS: {
1704                 DocIterator from, to;
1705                 if (cur.selection()) {
1706                         from = cur.selectionBegin();
1707                         to = cur.selectionEnd();
1708                 } else {
1709                         from = doc_iterator_begin(&buffer_);
1710                         to = doc_iterator_end(&buffer_);
1711                 }
1712                 buffer_.updateStatistics(from, to);
1713                 int const words = buffer_.wordCount();
1714                 int const chars = buffer_.charCount(false);
1715                 int const chars_blanks = buffer_.charCount(true);
1716                 docstring message;
1717                 if (cur.selection())
1718                         message = _("Statistics for the selection:");
1719                 else
1720                         message = _("Statistics for the document:");
1721                 message += "\n\n";
1722                 if (words != 1)
1723                         message += bformat(_("%1$d words"), words);
1724                 else
1725                         message += _("One word");
1726                 message += "\n";
1727                 if (chars_blanks != 1)
1728                         message += bformat(_("%1$d characters (including blanks)"),
1729                                           chars_blanks);
1730                 else
1731                         message += _("One character (including blanks)");
1732                 message += "\n";
1733                 if (chars != 1)
1734                         message += bformat(_("%1$d characters (excluding blanks)"),
1735                                           chars);
1736                 else
1737                         message += _("One character (excluding blanks)");
1738
1739                 Alert::information(_("Statistics"), message);
1740         }
1741                 break;
1742
1743         case LFUN_SCREEN_UP:
1744         case LFUN_SCREEN_DOWN: {
1745                 Point p = getPos(cur);
1746                 // This code has been commented out to enable to scroll down a
1747                 // document, even if there are large insets in it (see bug #5465).
1748                 /*if (p.y_ < 0 || p.y_ > height_) {
1749                         // The cursor is off-screen so recenter before proceeding.
1750                         showCursor();
1751                         p = getPos(cur);
1752                 }*/
1753                 int const scrolled = scroll(act == LFUN_SCREEN_UP
1754                         ? -height_ : height_);
1755                 if (act == LFUN_SCREEN_UP && scrolled > -height_)
1756                         p = Point(0, 0);
1757                 if (act == LFUN_SCREEN_DOWN && scrolled < height_)
1758                         p = Point(width_, height_);
1759                 bool const in_texted = cur.inTexted();
1760                 cur.setCursor(doc_iterator_begin(cur.buffer()));
1761                 cur.selHandle(false);
1762                 // Force an immediate computation of metrics because we need it below
1763                 processUpdateFlags(Update::Force);
1764
1765                 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1766                         true, act == LFUN_SCREEN_UP);
1767                 //FIXME: what to do with cur.x_target()?
1768                 bool update = in_texted && cur.bv().checkDepm(cur, old);
1769                 cur.finishUndo();
1770
1771                 if (update || cur.mark())
1772                         dr.screenUpdate(Update::Force | Update::FitCursor);
1773                 if (update)
1774                         dr.forceBufferUpdate();
1775                 break;
1776         }
1777
1778         case LFUN_SCROLL: {
1779                 string const scroll_type = cmd.getArg(0);
1780                 int scroll_step = 0;
1781                 if (scroll_type == "line")
1782                         scroll_step = d->scrollbarParameters_.single_step;
1783                 else if (scroll_type == "page")
1784                         scroll_step = d->scrollbarParameters_.page_step;
1785                 else
1786                         return;
1787                 string const scroll_quantity = cmd.getArg(1);
1788                 if (scroll_quantity == "up")
1789                         scrollUp(scroll_step);
1790                 else if (scroll_quantity == "down")
1791                         scrollDown(scroll_step);
1792                 else {
1793                         int const scroll_value = convert<int>(scroll_quantity);
1794                         if (scroll_value)
1795                                 scroll(scroll_step * scroll_value);
1796                 }
1797                 dr.screenUpdate(Update::ForceDraw);
1798                 dr.forceBufferUpdate();
1799                 break;
1800         }
1801
1802         case LFUN_SCREEN_UP_SELECT: {
1803                 // FIXME: why is the algorithm different from LFUN_SCREEN_UP?
1804                 cur.selHandle(true);
1805                 if (isTopScreen()) {
1806                         lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1807                         cur.finishUndo();
1808                         break;
1809                 }
1810                 int y = getPos(cur).y_;
1811                 int const ymin = y - height_ + defaultRowHeight();
1812                 while (y > ymin && cur.up())
1813                         y = getPos(cur).y_;
1814
1815                 cur.finishUndo();
1816                 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1817                 break;
1818         }
1819
1820         case LFUN_SCREEN_DOWN_SELECT: {
1821                 // FIXME: why is the algorithm different from LFUN_SCREEN_DOWN?
1822                 cur.selHandle(true);
1823                 if (isBottomScreen()) {
1824                         lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1825                         cur.finishUndo();
1826                         break;
1827                 }
1828                 int y = getPos(cur).y_;
1829                 int const ymax = y + height_ - defaultRowHeight();
1830                 while (y < ymax && cur.down())
1831                         y = getPos(cur).y_;
1832
1833                 cur.finishUndo();
1834                 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1835                 break;
1836         }
1837
1838
1839         case LFUN_INSET_SELECT_ALL: {
1840                 // true if all cells are selected
1841                 bool const all_selected = cur.depth() > 1
1842                     && cur.selBegin().at_begin()
1843                     && cur.selEnd().at_end();
1844                 // true if some cells are selected
1845                 bool const cells_selected = cur.depth() > 1
1846                     && cur.selBegin().at_cell_begin()
1847                         && cur.selEnd().at_cell_end();
1848                 if (all_selected || (cells_selected && !cur.inset().isTable())) {
1849                         // All the contents of the inset if selected, or only at
1850                         // least one cell but inset is not a table.
1851                         // Select the inset from outside.
1852                         cur.pop();
1853                         cur.resetAnchor();
1854                         cur.selection(true);
1855                         cur.posForward();
1856                 } else if (cells_selected) {
1857                         // At least one complete cell is selected and inset is a table.
1858                         // Select all cells
1859                         cur.idx() = 0;
1860                         cur.pos() = 0;
1861                         cur.resetAnchor();
1862                         cur.selection(true);
1863                         cur.idx() = cur.lastidx();
1864                         cur.pos() = cur.lastpos();
1865                 } else {
1866                         // select current cell
1867                         cur.pit() = 0;
1868                         cur.pos() = 0;
1869                         cur.resetAnchor();
1870                         cur.selection(true);
1871                         cur.pit() = cur.lastpit();
1872                         cur.pos() = cur.lastpos();
1873                 }
1874                 cur.setCurrentFont();
1875                 dr.screenUpdate(Update::Force);
1876                 break;
1877         }
1878
1879
1880         // This would be in Buffer class if only Cursor did not
1881         // require a bufferview
1882         case LFUN_INSET_FORALL: {
1883                 docstring const name = from_utf8(cmd.getArg(0));
1884                 string const commandstr = cmd.getLongArg(1);
1885                 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
1886
1887                 // an arbitrary number to limit number of iterations
1888                 const int max_iter = 100000;
1889                 int iterations = 0;
1890                 Cursor & cur = d->cursor_;
1891                 Cursor const savecur = cur;
1892                 cur.reset();
1893                 if (!cur.nextInset())
1894                         cur.forwardInset();
1895                 cur.beginUndoGroup();
1896                 while(cur && iterations < max_iter) {
1897                         Inset * const ins = cur.nextInset();
1898                         if (!ins)
1899                                 break;
1900                         docstring insname = ins->layoutName();
1901                         while (!insname.empty()) {
1902                                 if (insname == name || name == from_utf8("*")) {
1903                                         cur.recordUndo();
1904                                         lyx::dispatch(fr, dr);
1905                                         ++iterations;
1906                                         break;
1907                                 }
1908                                 size_t const i = insname.rfind(':');
1909                                 if (i == string::npos)
1910                                         break;
1911                                 insname = insname.substr(0, i);
1912                         }
1913                         // if we did not delete the inset, skip it
1914                         if (!cur.nextInset() || cur.nextInset() == ins)
1915                                 cur.forwardInset();
1916                 }
1917                 cur = savecur;
1918                 cur.fixIfBroken();
1919                 /** This is a dummy undo record only to remember the cursor
1920                  * that has just been set; this will be used on a redo action
1921                  * (see ticket #10097)
1922
1923                  * FIXME: a better fix would be to have a way to set the
1924                  * cursor value directly, but I am not sure it is worth it.
1925                  */
1926                 cur.recordUndo();
1927                 cur.endUndoGroup();
1928                 dr.screenUpdate(Update::Force);
1929                 dr.forceBufferUpdate();
1930
1931                 if (iterations >= max_iter) {
1932                         dr.setError(true);
1933                         dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
1934                 } else
1935                         dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
1936                 break;
1937         }
1938
1939
1940         case LFUN_BRANCH_ADD_INSERT: {
1941                 docstring branch_name = from_utf8(cmd.getArg(0));
1942                 if (branch_name.empty())
1943                         if (!Alert::askForText(branch_name, _("Branch name")) ||
1944                                                 branch_name.empty())
1945                                 break;
1946
1947                 DispatchResult drtmp;
1948                 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
1949                 if (drtmp.error()) {
1950                         Alert::warning(_("Branch already exists"), drtmp.message());
1951                         break;
1952                 }
1953                 BranchList & branch_list = buffer_.params().branchlist();
1954                 vector<docstring> const branches =
1955                         getVectorFromString(branch_name, branch_list.separator());
1956                 for (vector<docstring>::const_iterator it = branches.begin();
1957                      it != branches.end(); ++it) {
1958                         branch_name = *it;
1959                         lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch_name));
1960                 }
1961                 break;
1962         }
1963
1964         case LFUN_KEYMAP_OFF:
1965                 getIntl().keyMapOn(false);
1966                 break;
1967
1968         case LFUN_KEYMAP_PRIMARY:
1969                 getIntl().keyMapPrim();
1970                 break;
1971
1972         case LFUN_KEYMAP_SECONDARY:
1973                 getIntl().keyMapSec();
1974                 break;
1975
1976         case LFUN_KEYMAP_TOGGLE:
1977                 getIntl().toggleKeyMap();
1978                 break;
1979
1980         case LFUN_DIALOG_SHOW_NEW_INSET: {
1981                 string const name = cmd.getArg(0);
1982                 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1983                 if (decodeInsetParam(name, data, buffer_))
1984                         lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1985                 else
1986                         lyxerr << "Inset type '" << name <<
1987                         "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" <<  endl;
1988                 break;
1989         }
1990
1991         case LFUN_CITATION_INSERT: {
1992                 if (argument.empty()) {
1993                         lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1994                         break;
1995                 }
1996                 // we can have one optional argument, delimited by '|'
1997                 // citation-insert <key>|<text_before>
1998                 // this should be enhanced to also support text_after
1999                 // and citation style
2000                 string arg = argument;
2001                 string opt1;
2002                 if (contains(argument, "|")) {
2003                         arg = token(argument, '|', 0);
2004                         opt1 = token(argument, '|', 1);
2005                 }
2006
2007                 // if our cursor is directly in front of or behind a citation inset,
2008                 // we will instead add the new key to it.
2009                 Inset * inset = cur.nextInset();
2010                 if (!inset || inset->lyxCode() != CITE_CODE)
2011                         inset = cur.prevInset();
2012                 if (inset && inset->lyxCode() == CITE_CODE) {
2013                         InsetCitation * icite = static_cast<InsetCitation *>(inset);
2014                         if (icite->addKey(arg)) {
2015                                 dr.forceBufferUpdate();
2016                                 dr.screenUpdate(Update::FitCursor | Update::SinglePar);
2017                                 if (!opt1.empty())
2018                                         LYXERR0("Discarding optional argument to citation-insert.");
2019                         }
2020                         dispatched = true;
2021                         break;
2022                 }
2023                 InsetCommandParams icp(CITE_CODE);
2024                 icp["key"] = from_utf8(arg);
2025                 if (!opt1.empty())
2026                         icp["before"] = from_utf8(opt1);
2027                 string icstr = InsetCommand::params2string(icp);
2028                 FuncRequest fr(LFUN_INSET_INSERT, icstr);
2029                 lyx::dispatch(fr);
2030                 break;
2031         }
2032
2033         case LFUN_INSET_APPLY: {
2034                 string const name = cmd.getArg(0);
2035                 Inset * inset = editedInset(name);
2036                 if (!inset) {
2037                         FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
2038                         lyx::dispatch(fr);
2039                         break;
2040                 }
2041                 // put cursor in front of inset.
2042                 if (!setCursorFromInset(inset)) {
2043                         LASSERT(false, break);
2044                 }
2045                 cur.recordUndo();
2046                 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
2047                 inset->dispatch(cur, fr);
2048                 dr.screenUpdate(cur.result().screenUpdate());
2049                 if (cur.result().needBufferUpdate())
2050                         dr.forceBufferUpdate();
2051                 break;
2052         }
2053
2054         // FIXME:
2055         // The change of language of buffer belongs to the Buffer class.
2056         // We have to do it here because we need a cursor for Undo.
2057         // When Undo::recordUndoBufferParams() is implemented someday
2058         // LFUN_BUFFER_LANGUAGE should be handled by the Buffer class.
2059         case LFUN_BUFFER_LANGUAGE: {
2060                 Language const * oldL = buffer_.params().language;
2061                 Language const * newL = languages.getLanguage(argument);
2062                 if (!newL || oldL == newL)
2063                         break;
2064                 if (oldL->rightToLeft() == newL->rightToLeft()) {
2065                         cur.recordUndoFullBuffer();
2066                         buffer_.changeLanguage(oldL, newL);
2067                         cur.setCurrentFont();
2068                         dr.forceBufferUpdate();
2069                 }
2070                 break;
2071         }
2072
2073         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2074         case LFUN_FILE_INSERT_PLAINTEXT: {
2075                 bool const as_paragraph = (act == LFUN_FILE_INSERT_PLAINTEXT_PARA);
2076                 string const fname = to_utf8(cmd.argument());
2077                 if (!FileName::isAbsolute(fname))
2078                         dr.setMessage(_("Absolute filename expected."));
2079                 else
2080                         insertPlaintextFile(FileName(fname), as_paragraph);
2081                 break;
2082         }
2083
2084         default:
2085                 // OK, so try the Buffer itself...
2086                 buffer_.dispatch(cmd, dr);
2087                 dispatched = dr.dispatched();
2088                 break;
2089         }
2090
2091         buffer_.undo().endUndoGroup();
2092         dr.dispatched(dispatched);
2093
2094         // NOTE: The code below is copied from Cursor::dispatch. If you
2095         // need to modify this, please update the other one too.
2096
2097         // notify insets we just entered/left
2098         if (cursor() != old) {
2099                 old.beginUndoGroup();
2100                 old.fixIfBroken();
2101                 bool badcursor = notifyCursorLeavesOrEnters(old, cursor());
2102                 if (badcursor) {
2103                         cursor().fixIfBroken();
2104                         resetInlineCompletionPos();
2105                 }
2106                 old.endUndoGroup();
2107         }
2108 }
2109
2110
2111 docstring const BufferView::requestSelection()
2112 {
2113         Cursor & cur = d->cursor_;
2114
2115         LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
2116         if (!cur.selection()) {
2117                 d->xsel_cache_.set = false;
2118                 return docstring();
2119         }
2120
2121         LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
2122         if (!d->xsel_cache_.set ||
2123             cur.top() != d->xsel_cache_.cursor ||
2124             cur.realAnchor().top() != d->xsel_cache_.anchor)
2125         {
2126                 d->xsel_cache_.cursor = cur.top();
2127                 d->xsel_cache_.anchor = cur.realAnchor().top();
2128                 d->xsel_cache_.set = cur.selection();
2129                 return cur.selectionAsString(false);
2130         }
2131         return docstring();
2132 }
2133
2134
2135 void BufferView::clearSelection()
2136 {
2137         d->cursor_.clearSelection();
2138         // Clear the selection buffer. Otherwise a subsequent
2139         // middle-mouse-button paste would use the selection buffer,
2140         // not the more current external selection.
2141         cap::clearSelection();
2142         d->xsel_cache_.set = false;
2143         // The buffer did not really change, but this causes the
2144         // redraw we need because we cleared the selection above.
2145         buffer_.changed(false);
2146 }
2147
2148
2149 void BufferView::resize(int width, int height)
2150 {
2151         // Update from work area
2152         width_ = width;
2153         height_ = height;
2154
2155         // Clear the paragraph height cache.
2156         d->par_height_.clear();
2157         // Redo the metrics.
2158         updateMetrics();
2159 }
2160
2161
2162 Inset const * BufferView::getCoveringInset(Text const & text,
2163                 int x, int y) const
2164 {
2165         TextMetrics & tm = d->text_metrics_[&text];
2166         Inset * inset = tm.checkInsetHit(x, y);
2167         if (!inset)
2168                 return 0;
2169
2170         if (!inset->descendable(*this))
2171                 // No need to go further down if the inset is not
2172                 // descendable.
2173                 return inset;
2174
2175         size_t cell_number = inset->nargs();
2176         // Check all the inner cell.
2177         for (size_t i = 0; i != cell_number; ++i) {
2178                 Text const * inner_text = inset->getText(i);
2179                 if (inner_text) {
2180                         // Try deeper.
2181                         Inset const * inset_deeper =
2182                                 getCoveringInset(*inner_text, x, y);
2183                         if (inset_deeper)
2184                                 return inset_deeper;
2185                 }
2186         }
2187
2188         return inset;
2189 }
2190
2191
2192 void BufferView::updateHoveredInset() const
2193 {
2194         // Get inset under mouse, if there is one.
2195         int const x = d->mouse_position_cache_.x_;
2196         int const y = d->mouse_position_cache_.y_;
2197         Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
2198
2199         d->clickable_inset_ = covering_inset && covering_inset->clickable(*this, x, y);
2200
2201         if (covering_inset == d->last_inset_)
2202                 // Same inset, no need to do anything...
2203                 return;
2204
2205         bool need_redraw = false;
2206         if (d->last_inset_) {
2207                 // Remove the hint on the last hovered inset (if any).
2208                 need_redraw |= d->last_inset_->setMouseHover(this, false);
2209                 d->last_inset_ = 0;
2210         }
2211
2212         if (covering_inset && covering_inset->setMouseHover(this, true)) {
2213                 need_redraw = true;
2214                 // Only the insets that accept the hover state, do
2215                 // clear the last_inset_, so only set the last_inset_
2216                 // member if the hovered setting is accepted.
2217                 d->last_inset_ = covering_inset;
2218         }
2219
2220         if (need_redraw) {
2221                 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
2222                                 << d->mouse_position_cache_.x_ << ", "
2223                                 << d->mouse_position_cache_.y_ << ")");
2224
2225                 d->update_strategy_ = DecorationUpdate;
2226
2227                 // This event (moving without mouse click) is not passed further.
2228                 // This should be changed if it is further utilized.
2229                 buffer_.changed(false);
2230         }
2231 }
2232
2233
2234 void BufferView::clearLastInset(Inset * inset) const
2235 {
2236         if (d->last_inset_ != inset) {
2237                 LYXERR0("Wrong last_inset!");
2238                 LATTEST(false);
2239         }
2240         d->last_inset_ = 0;
2241 }
2242
2243
2244 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
2245 {
2246         //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
2247
2248         // This is only called for mouse related events including
2249         // LFUN_FILE_OPEN generated by drag-and-drop.
2250         FuncRequest cmd = cmd0;
2251
2252         Cursor old = cursor();
2253         Cursor cur(*this);
2254         cur.push(buffer_.inset());
2255         cur.selection(d->cursor_.selection());
2256
2257         // Either the inset under the cursor or the
2258         // surrounding Text will handle this event.
2259
2260         // make sure we stay within the screen...
2261         cmd.set_y(min(max(cmd.y(), -1), height_));
2262
2263         d->mouse_position_cache_.x_ = cmd.x();
2264         d->mouse_position_cache_.y_ = cmd.y();
2265
2266         if (cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
2267                 updateHoveredInset();
2268                 return;
2269         }
2270
2271         // Build temporary cursor.
2272         Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x(), cmd.y());
2273         if (inset) {
2274                 // If inset is not editable, cur.pos() might point behind the
2275                 // inset (depending on cmd.x(), cmd.y()). This is needed for
2276                 // editing to fix bug 9628, but e.g. the context menu needs a
2277                 // cursor in front of the inset.
2278                 if ((inset->hasSettings() || !inset->contextMenuName().empty()
2279                      || inset->lyxCode() == SEPARATOR_CODE) &&
2280                     cur.nextInset() != inset && cur.prevInset() == inset)
2281                         cur.posBackward();
2282         } else if (cur.inTexted() && cur.pos()
2283                         && cur.paragraph().isEnvSeparator(cur.pos() - 1)) {
2284                 // Always place cursor in front of a separator inset.
2285                 cur.posBackward();
2286         }
2287
2288         // Put anchor at the same position.
2289         cur.resetAnchor();
2290
2291         cur.beginUndoGroup();
2292
2293         // Try to dispatch to an non-editable inset near this position
2294         // via the temp cursor. If the inset wishes to change the real
2295         // cursor it has to do so explicitly by using
2296         //  cur.bv().cursor() = cur;  (or similar)
2297         if (inset)
2298                 inset->dispatch(cur, cmd);
2299
2300         // Now dispatch to the temporary cursor. If the real cursor should
2301         // be modified, the inset's dispatch has to do so explicitly.
2302         if (!inset || !cur.result().dispatched())
2303                 cur.dispatch(cmd);
2304
2305         // Notify left insets
2306         if (cur != old) {
2307                 bool badcursor = old.fixIfBroken() | cur.fixIfBroken();
2308                 badcursor |= notifyCursorLeavesOrEnters(old, cur);
2309                 if (badcursor)
2310                         cursor().fixIfBroken();
2311         }
2312
2313         cur.endUndoGroup();
2314
2315         // Do we have a selection?
2316         theSelection().haveSelection(cursor().selection());
2317
2318         if (cur.needBufferUpdate()) {
2319                 cur.clearBufferUpdate();
2320                 buffer().updateBuffer();
2321         }
2322
2323         // If the command has been dispatched,
2324         if (cur.result().dispatched() || cur.result().screenUpdate())
2325                 processUpdateFlags(cur.result().screenUpdate());
2326 }
2327
2328
2329 int BufferView::minVisiblePart()
2330 {
2331         return 2 * defaultRowHeight();
2332 }
2333
2334
2335 int BufferView::scroll(int y)
2336 {
2337         if (y > 0)
2338                 return scrollDown(y);
2339         if (y < 0)
2340                 return scrollUp(-y);
2341         return 0;
2342 }
2343
2344
2345 int BufferView::scrollDown(int offset)
2346 {
2347         Text * text = &buffer_.text();
2348         TextMetrics & tm = d->text_metrics_[text];
2349         int const ymax = height_ + offset;
2350         while (true) {
2351                 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2352                 int bottom_pos = last.second->position() + last.second->descent();
2353                 if (lyxrc.scroll_below_document)
2354                         bottom_pos += height_ - minVisiblePart();
2355                 if (last.first + 1 == int(text->paragraphs().size())) {
2356                         if (bottom_pos <= height_)
2357                                 return 0;
2358                         offset = min(offset, bottom_pos - height_);
2359                         break;
2360                 }
2361                 if (bottom_pos > ymax)
2362                         break;
2363                 tm.newParMetricsDown();
2364         }
2365         d->anchor_ypos_ -= offset;
2366         return -offset;
2367 }
2368
2369
2370 int BufferView::scrollUp(int offset)
2371 {
2372         Text * text = &buffer_.text();
2373         TextMetrics & tm = d->text_metrics_[text];
2374         int ymin = - offset;
2375         while (true) {
2376                 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2377                 int top_pos = first.second->position() - first.second->ascent();
2378                 if (first.first == 0) {
2379                         if (top_pos >= 0)
2380                                 return 0;
2381                         offset = min(offset, - top_pos);
2382                         break;
2383                 }
2384                 if (top_pos < ymin)
2385                         break;
2386                 tm.newParMetricsUp();
2387         }
2388         d->anchor_ypos_ += offset;
2389         return offset;
2390 }
2391
2392
2393 bool BufferView::setCursorFromRow(int row)
2394 {
2395         TexRow::TextEntry start, end;
2396         tie(start,end) = buffer_.texrow().getEntriesFromRow(row);
2397         LYXERR(Debug::LATEX,
2398                "setCursorFromRow: for row " << row << ", TexRow has found "
2399                "start (id=" << start.id << ",pos=" << start.pos << "), "
2400                "end (id=" << end.id << ",pos=" << end.pos << ")");
2401         return setCursorFromEntries(start, end);
2402 }
2403
2404
2405 bool BufferView::setCursorFromEntries(TexRow::TextEntry start,
2406                                       TexRow::TextEntry end)
2407 {
2408         DocIterator dit_start, dit_end;
2409         tie(dit_start,dit_end) =
2410                 TexRow::getDocIteratorsFromEntries(start, end, buffer_);
2411         if (!dit_start)
2412                 return false;
2413         // Setting selection start
2414         d->cursor_.clearSelection();
2415         setCursor(dit_start);
2416         // Setting selection end
2417         if (dit_end) {
2418                 d->cursor_.resetAnchor();
2419                 setCursorSelectionTo(dit_end);
2420         }
2421         return true;
2422 }
2423
2424
2425 bool BufferView::setCursorFromInset(Inset const * inset)
2426 {
2427         // are we already there?
2428         if (cursor().nextInset() == inset)
2429                 return true;
2430
2431         // Inset is not at cursor position. Find it in the document.
2432         Cursor cur(*this);
2433         cur.reset();
2434         while (cur && cur.nextInset() != inset)
2435                 cur.forwardInset();
2436
2437         if (cur) {
2438                 setCursor(cur);
2439                 return true;
2440         }
2441         return false;
2442 }
2443
2444
2445 void BufferView::gotoLabel(docstring const & label)
2446 {
2447         ListOfBuffers bufs = buffer().allRelatives();
2448         ListOfBuffers::iterator it = bufs.begin();
2449         for (; it != bufs.end(); ++it) {
2450                 Buffer const * buf = *it;
2451
2452                 // find label
2453                 shared_ptr<Toc> toc = buf->tocBackend().toc("label");
2454                 Toc::const_iterator toc_it = toc->begin();
2455                 Toc::const_iterator end = toc->end();
2456                 for (; toc_it != end; ++toc_it) {
2457                         if (label == toc_it->str()) {
2458                                 lyx::dispatch(toc_it->action());
2459                                 return;
2460                         }
2461                 }
2462         }
2463 }
2464
2465
2466 TextMetrics const & BufferView::textMetrics(Text const * t) const
2467 {
2468         return const_cast<BufferView *>(this)->textMetrics(t);
2469 }
2470
2471
2472 TextMetrics & BufferView::textMetrics(Text const * t)
2473 {
2474         LBUFERR(t);
2475         TextMetricsCache::iterator tmc_it  = d->text_metrics_.find(t);
2476         if (tmc_it == d->text_metrics_.end()) {
2477                 tmc_it = d->text_metrics_.insert(
2478                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
2479         }
2480         return tmc_it->second;
2481 }
2482
2483
2484 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2485                 pit_type pit) const
2486 {
2487         return textMetrics(t).parMetrics(pit);
2488 }
2489
2490
2491 int BufferView::workHeight() const
2492 {
2493         return height_;
2494 }
2495
2496
2497 void BufferView::setCursor(DocIterator const & dit)
2498 {
2499         d->cursor_.reset();
2500         size_t const n = dit.depth();
2501         for (size_t i = 0; i < n; ++i)
2502                 dit[i].inset().edit(d->cursor_, true);
2503
2504         d->cursor_.setCursor(dit);
2505         d->cursor_.selection(false);
2506         d->cursor_.setCurrentFont();
2507         // FIXME
2508         // It seems on general grounds as if this is probably needed, but
2509         // it is not yet clear.
2510         // See bug #7394 and r38388.
2511         // d->cursor.resetAnchor();
2512 }
2513
2514
2515 void BufferView::setCursorSelectionTo(DocIterator const & dit)
2516 {
2517         size_t const n = dit.depth();
2518         for (size_t i = 0; i < n; ++i)
2519                 dit[i].inset().edit(d->cursor_, true);
2520
2521         d->cursor_.selection(true);
2522         d->cursor_.setCursorSelectionTo(dit);
2523         d->cursor_.setCurrentFont();
2524 }
2525
2526
2527 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2528 {
2529         // Would be wrong to delete anything if we have a selection.
2530         if (cur.selection())
2531                 return false;
2532
2533         bool need_anchor_change = false;
2534         bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
2535                 need_anchor_change);
2536
2537         if (need_anchor_change)
2538                 cur.resetAnchor();
2539
2540         if (!changed)
2541                 return false;
2542
2543         d->cursor_ = cur;
2544
2545         // we would rather not do this here, but it needs to be done before
2546         // the changed() signal is sent.
2547         buffer_.updateBuffer();
2548
2549         buffer_.changed(true);
2550         return true;
2551 }
2552
2553
2554 bool BufferView::mouseSetCursor(Cursor & cur, bool const select)
2555 {
2556         LASSERT(&cur.bv() == this, return false);
2557
2558         if (!select)
2559                 // this event will clear selection so we save selection for
2560                 // persistent selection
2561                 cap::saveSelection(cursor());
2562
2563         d->cursor_.macroModeClose();
2564         // If a macro has been finalized, the cursor might have been broken
2565         cur.fixIfBroken();
2566
2567         // Has the cursor just left the inset?
2568         bool const leftinset = (&d->cursor_.inset() != &cur.inset());
2569         if (leftinset)
2570                 d->cursor_.fixIfBroken();
2571
2572         // do the dEPM magic if needed
2573         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2574         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2575         // the leftinset bool would not be necessary (badcursor instead).
2576         bool update = leftinset;
2577
2578         if (select) {
2579                 d->cursor_.setSelection();
2580                 d->cursor_.setCursorSelectionTo(cur);
2581         } else {
2582                 if (d->cursor_.inTexted())
2583                         update |= checkDepm(cur, d->cursor_);
2584                 d->cursor_.resetAnchor();
2585                 d->cursor_.setCursor(cur);
2586                 d->cursor_.clearSelection();
2587         }
2588         d->cursor_.boundary(cur.boundary());
2589         d->cursor_.finishUndo();
2590         d->cursor_.setCurrentFont();
2591         if (update)
2592                 cur.forceBufferUpdate();
2593         return update;
2594 }
2595
2596
2597 void BufferView::putSelectionAt(DocIterator const & cur,
2598                                 int length, bool backwards)
2599 {
2600         d->cursor_.clearSelection();
2601
2602         setCursor(cur);
2603
2604         if (length) {
2605                 if (backwards) {
2606                         d->cursor_.pos() += length;
2607                         d->cursor_.setSelection(d->cursor_, -length);
2608                 } else
2609                         d->cursor_.setSelection(d->cursor_, length);
2610         }
2611 }
2612
2613
2614 bool BufferView::selectIfEmpty(DocIterator & cur)
2615 {
2616         if ((cur.inTexted() && !cur.paragraph().empty())
2617             || (cur.inMathed() && !cur.cell().empty()))
2618                 return false;
2619
2620         pit_type const beg_pit = cur.pit();
2621         if (beg_pit > 0) {
2622                 // The paragraph associated to this item isn't
2623                 // the first one, so it can be selected
2624                 cur.backwardPos();
2625         } else {
2626                 // We have to resort to select the space between the
2627                 // end of this item and the begin of the next one
2628                 cur.forwardPos();
2629         }
2630         if (cur.empty()) {
2631                 // If it is the only item in the document,
2632                 // nothing can be selected
2633                 return false;
2634         }
2635         pit_type const end_pit = cur.pit();
2636         pos_type const end_pos = cur.pos();
2637         d->cursor_.clearSelection();
2638         d->cursor_.reset();
2639         d->cursor_.setCursor(cur);
2640         d->cursor_.pit() = beg_pit;
2641         d->cursor_.pos() = 0;
2642         d->cursor_.selection(false);
2643         d->cursor_.resetAnchor();
2644         d->cursor_.pit() = end_pit;
2645         d->cursor_.pos() = end_pos;
2646         d->cursor_.setSelection();
2647         return true;
2648 }
2649
2650
2651 Cursor & BufferView::cursor()
2652 {
2653         return d->cursor_;
2654 }
2655
2656
2657 Cursor const & BufferView::cursor() const
2658 {
2659         return d->cursor_;
2660 }
2661
2662
2663 pit_type BufferView::anchor_ref() const
2664 {
2665         return d->anchor_pit_;
2666 }
2667
2668
2669 bool BufferView::singleParUpdate()
2670 {
2671         Text & buftext = buffer_.text();
2672         pit_type const bottom_pit = d->cursor_.bottom().pit();
2673         TextMetrics & tm = textMetrics(&buftext);
2674         int old_height = tm.parMetrics(bottom_pit).height();
2675
2676         // make sure inline completion pointer is ok
2677         if (d->inlineCompletionPos_.fixIfBroken())
2678                 d->inlineCompletionPos_ = DocIterator();
2679
2680         // In Single Paragraph mode, rebreak only
2681         // the (main text, not inset!) paragraph containing the cursor.
2682         // (if this paragraph contains insets etc., rebreaking will
2683         // recursively descend)
2684         tm.redoParagraph(bottom_pit);
2685         ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
2686         if (pm.height() != old_height)
2687                 // Paragraph height has changed so we cannot proceed to
2688                 // the singlePar optimisation.
2689                 return false;
2690
2691         tm.updatePosCache(bottom_pit);
2692
2693         LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2694                 << " y2: " << pm.position() + pm.descent()
2695                 << " pit: " << bottom_pit
2696                 << " singlepar: 1");
2697         return true;
2698 }
2699
2700
2701 void BufferView::updateMetrics()
2702 {
2703         updateMetrics(d->update_flags_);
2704         d->update_strategy_ = FullScreenUpdate;
2705 }
2706
2707
2708 void BufferView::updateMetrics(Update::flags & update_flags)
2709 {
2710         if (height_ == 0 || width_ == 0)
2711                 return;
2712
2713         Text & buftext = buffer_.text();
2714         pit_type const npit = int(buftext.paragraphs().size());
2715
2716         // Clear out the position cache in case of full screen redraw,
2717         d->coord_cache_.clear();
2718
2719         // Clear out paragraph metrics to avoid having invalid metrics
2720         // in the cache from paragraphs not relayouted below
2721         // The complete text metrics will be redone.
2722         d->text_metrics_.clear();
2723
2724         TextMetrics & tm = textMetrics(&buftext);
2725
2726         // make sure inline completion pointer is ok
2727         if (d->inlineCompletionPos_.fixIfBroken())
2728                 d->inlineCompletionPos_ = DocIterator();
2729
2730         if (d->anchor_pit_ >= npit)
2731                 // The anchor pit must have been deleted...
2732                 d->anchor_pit_ = npit - 1;
2733
2734         // Rebreak anchor paragraph.
2735         tm.redoParagraph(d->anchor_pit_);
2736         ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2737
2738         // position anchor
2739         if (d->anchor_pit_ == 0) {
2740                 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2741
2742                 // Complete buffer visible? Then it's easy.
2743                 if (scrollRange == 0)
2744                         d->anchor_ypos_ = anchor_pm.ascent();
2745                 else {
2746                         // avoid empty space above the first row
2747                         d->anchor_ypos_ = min(d->anchor_ypos_, anchor_pm.ascent());
2748                 }
2749         }
2750         anchor_pm.setPosition(d->anchor_ypos_);
2751         tm.updatePosCache(d->anchor_pit_);
2752
2753         LYXERR(Debug::PAINTING, "metrics: "
2754                 << " anchor pit = " << d->anchor_pit_
2755                 << " anchor ypos = " << d->anchor_ypos_);
2756
2757         // Redo paragraphs above anchor if necessary.
2758         int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2759         // We are now just above the anchor paragraph.
2760         pit_type pit1 = d->anchor_pit_ - 1;
2761         for (; pit1 >= 0 && y1 >= 0; --pit1) {
2762                 tm.redoParagraph(pit1);
2763                 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2764                 y1 -= pm.descent();
2765                 // Save the paragraph position in the cache.
2766                 pm.setPosition(y1);
2767                 tm.updatePosCache(pit1);
2768                 y1 -= pm.ascent();
2769         }
2770
2771         // Redo paragraphs below the anchor if necessary.
2772         int y2 = d->anchor_ypos_ + anchor_pm.descent();
2773         // We are now just below the anchor paragraph.
2774         pit_type pit2 = d->anchor_pit_ + 1;
2775         for (; pit2 < npit && y2 <= height_; ++pit2) {
2776                 tm.redoParagraph(pit2);
2777                 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2778                 y2 += pm.ascent();
2779                 // Save the paragraph position in the cache.
2780                 pm.setPosition(y2);
2781                 tm.updatePosCache(pit2);
2782                 y2 += pm.descent();
2783         }
2784
2785         LYXERR(Debug::PAINTING, "Metrics: "
2786                 << " anchor pit = " << d->anchor_pit_
2787                 << " anchor ypos = " << d->anchor_ypos_
2788                 << " y1 = " << y1
2789                 << " y2 = " << y2
2790                 << " pit1 = " << pit1
2791                 << " pit2 = " << pit2);
2792
2793         // metrics is done, full drawing is necessary now
2794         update_flags = (update_flags & ~Update::Force) | Update::ForceDraw;
2795
2796         // Now update the positions of insets in the cache.
2797         updatePosCache();
2798
2799         if (lyxerr.debugging(Debug::WORKAREA)) {
2800                 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2801                 d->coord_cache_.dump();
2802         }
2803 }
2804
2805
2806 void BufferView::updatePosCache()
2807 {
2808         // this is the "nodraw" drawing stage: only set the positions of the
2809         // insets in metrics cache.
2810         frontend::NullPainter np;
2811         draw(np, false);
2812 }
2813
2814
2815 void BufferView::insertLyXFile(FileName const & fname)
2816 {
2817         LASSERT(d->cursor_.inTexted(), return);
2818
2819         // Get absolute path of file and add ".lyx"
2820         // to the filename if necessary
2821         FileName filename = fileSearch(string(), fname.absFileName(), "lyx");
2822
2823         docstring const disp_fn = makeDisplayPath(filename.absFileName());
2824         // emit message signal.
2825         message(bformat(_("Inserting document %1$s..."), disp_fn));
2826
2827         docstring res;
2828         Buffer buf(filename.absFileName(), false);
2829         if (buf.loadLyXFile() == Buffer::ReadSuccess) {
2830                 ErrorList & el = buffer_.errorList("Parse");
2831                 // Copy the inserted document error list into the current buffer one.
2832                 el = buf.errorList("Parse");
2833                 buffer_.undo().recordUndo(d->cursor_);
2834                 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2835                                              buf.params().documentClassPtr(), el);
2836                 res = _("Document %1$s inserted.");
2837         } else {
2838                 res = _("Could not insert document %1$s");
2839         }
2840
2841         buffer_.changed(true);
2842         // emit message signal.
2843         message(bformat(res, disp_fn));
2844 }
2845
2846
2847 Point BufferView::coordOffset(DocIterator const & dit) const
2848 {
2849         int x = 0;
2850         int y = 0;
2851         int lastw = 0;
2852
2853         // Addup contribution of nested insets, from inside to outside,
2854         // keeping the outer paragraph for a special handling below
2855         for (size_t i = dit.depth() - 1; i >= 1; --i) {
2856                 CursorSlice const & sl = dit[i];
2857                 int xx = 0;
2858                 int yy = 0;
2859
2860                 // get relative position inside sl.inset()
2861                 sl.inset().cursorPos(*this, sl, dit.boundary() && (i + 1 == dit.depth()), xx, yy);
2862
2863                 // Make relative position inside of the edited inset relative to sl.inset()
2864                 x += xx;
2865                 y += yy;
2866
2867                 // In case of an RTL inset, the edited inset will be positioned to the left
2868                 // of xx:yy
2869                 if (sl.text()) {
2870                         bool boundary_i = dit.boundary() && i + 1 == dit.depth();
2871                         bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2872                         if (rtl)
2873                                 x -= lastw;
2874                 }
2875
2876                 // remember width for the case that sl.inset() is positioned in an RTL inset
2877                 lastw = sl.inset().dimension(*this).wid;
2878
2879                 //lyxerr << "Cursor::getPos, i: "
2880                 // << i << " x: " << xx << " y: " << y << endl;
2881         }
2882
2883         // Add contribution of initial rows of outermost paragraph
2884         CursorSlice const & sl = dit[0];
2885         TextMetrics const & tm = textMetrics(sl.text());
2886         ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2887
2888         LBUFERR(!pm.rows().empty());
2889         y -= pm.rows()[0].ascent();
2890 #if 1
2891         // FIXME: document this mess
2892         size_t rend;
2893         if (sl.pos() > 0 && dit.depth() == 1) {
2894                 int pos = sl.pos();
2895                 if (pos && dit.boundary())
2896                         --pos;
2897 //              lyxerr << "coordOffset: boundary:" << dit.boundary() << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2898                 rend = pm.pos2row(pos);
2899         } else
2900                 rend = pm.pos2row(sl.pos());
2901 #else
2902         size_t rend = pm.pos2row(sl.pos());
2903 #endif
2904         for (size_t rit = 0; rit != rend; ++rit)
2905                 y += pm.rows()[rit].height();
2906         y += pm.rows()[rend].ascent();
2907
2908         TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2909
2910         // Make relative position from the nested inset now bufferview absolute.
2911         int xx = bottom_tm.cursorX(dit.bottom(), dit.boundary() && dit.depth() == 1);
2912         x += xx;
2913
2914         // In the RTL case place the nested inset at the left of the cursor in
2915         // the outer paragraph
2916         bool boundary_1 = dit.boundary() && 1 == dit.depth();
2917         bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2918         if (rtl)
2919                 x -= lastw;
2920
2921         return Point(x, y);
2922 }
2923
2924
2925 Point BufferView::getPos(DocIterator const & dit) const
2926 {
2927         if (!paragraphVisible(dit))
2928                 return Point(-1, -1);
2929
2930         CursorSlice const & bot = dit.bottom();
2931         TextMetrics const & tm = textMetrics(bot.text());
2932
2933         // offset from outer paragraph
2934         Point p = coordOffset(dit);
2935         p.y_ += tm.parMetrics(bot.pit()).position();
2936         return p;
2937 }
2938
2939
2940 bool BufferView::paragraphVisible(DocIterator const & dit) const
2941 {
2942         CursorSlice const & bot = dit.bottom();
2943         TextMetrics const & tm = textMetrics(bot.text());
2944
2945         return tm.contains(bot.pit());
2946 }
2947
2948
2949 void BufferView::caretPosAndHeight(Point & p, int & h) const
2950 {
2951         Cursor const & cur = cursor();
2952         Font const font = cur.real_current_font;
2953         frontend::FontMetrics const & fm = theFontMetrics(font);
2954         int const asc = fm.maxAscent();
2955         int const des = fm.maxDescent();
2956         h = asc + des;
2957         p = getPos(cur);
2958         p.y_ -= asc;
2959 }
2960
2961
2962 bool BufferView::cursorInView(Point const & p, int h) const
2963 {
2964         Cursor const & cur = cursor();
2965         // does the cursor touch the screen ?
2966         if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
2967                 return false;
2968         return true;
2969 }
2970
2971
2972 int BufferView::horizScrollOffset() const
2973 {
2974         return d->horiz_scroll_offset_;
2975 }
2976
2977
2978 int BufferView::horizScrollOffset(Text const * text,
2979                                   pit_type pit, pos_type pos) const
2980 {
2981         // Is this a row that is currently scrolled?
2982         if (!d->current_row_slice_.empty()
2983             && &text->inset() == d->current_row_slice_.inset().asInsetText()
2984             && pit ==  d->current_row_slice_.pit()
2985             && pos ==  d->current_row_slice_.pos())
2986                 return d->horiz_scroll_offset_;
2987         return 0;
2988 }
2989
2990
2991 bool BufferView::hadHorizScrollOffset(Text const * text,
2992                                       pit_type pit, pos_type pos) const
2993 {
2994         return !d->last_row_slice_.empty()
2995                && &text->inset() == d->last_row_slice_.inset().asInsetText()
2996                && pit ==  d->last_row_slice_.pit()
2997                && pos ==  d->last_row_slice_.pos();
2998 }
2999
3000
3001 void BufferView::setCurrentRowSlice(CursorSlice const & rowSlice)
3002 {
3003         // nothing to do if the cursor was already on this row
3004         if (d->current_row_slice_ == rowSlice) {
3005                 d->last_row_slice_ = CursorSlice();
3006                 return;
3007         }
3008
3009         // if the (previous) current row was scrolled, we have to
3010         // remember it in order to repaint it next time.
3011         if (d->horiz_scroll_offset_ != 0)
3012                 d->last_row_slice_ = d->current_row_slice_;
3013         else
3014                 d->last_row_slice_ = CursorSlice();
3015
3016         // Since we changed row, the scroll offset is not valid anymore
3017         d->horiz_scroll_offset_ = 0;
3018         d->current_row_slice_ = rowSlice;
3019 }
3020
3021
3022 namespace {
3023
3024 bool sliceInRow(CursorSlice const & cs, Text const * text, Row const & row)
3025 {
3026         /* The normal case is the last line. The previous line takes care
3027          * of empty rows (e.g. empty paragraphs). Cursor boundary issues
3028          * are taken care of when setting caret_slice_ in
3029          * BufferView::draw.
3030          */
3031         return !cs.empty() && cs.text() == text && cs.pit() == row.pit()
3032                && ((row.pos() == row.endpos() && row.pos() == cs.pos())
3033                   || (row.pos() <= cs.pos() && cs.pos() < row.endpos()));
3034 }
3035
3036 }
3037
3038
3039 bool BufferView::needRepaint(Text const * text, Row const & row) const
3040 {
3041         return d->repaint_caret_row_ && sliceInRow(d->caret_slice_, text, row);
3042 }
3043
3044
3045 void BufferView::checkCursorScrollOffset()
3046 {
3047         CursorSlice rowSlice = d->cursor_.bottom();
3048         TextMetrics const & tm = textMetrics(rowSlice.text());
3049
3050         // Stop if metrics have not been computed yet, since it means
3051         // that there is nothing to do.
3052         if (!tm.contains(rowSlice.pit()))
3053                 return;
3054         ParagraphMetrics const & pm = tm.parMetrics(rowSlice.pit());
3055         Row const & row = pm.getRow(rowSlice.pos(),
3056                                     d->cursor_.boundary() && rowSlice == d->cursor_.top());
3057         rowSlice.pos() = row.pos();
3058
3059         // Set the row on which the cursor lives.
3060         setCurrentRowSlice(rowSlice);
3061
3062         // Current x position of the cursor in pixels
3063         int cur_x = getPos(d->cursor_).x_;
3064
3065         // Horizontal scroll offset of the cursor row in pixels
3066         int offset = d->horiz_scroll_offset_;
3067         int const MARGIN = 2 * theFontMetrics(d->cursor_.real_current_font).em()
3068                            + row.right_margin;
3069         if (row.right_x() <= workWidth() - row.right_margin) {
3070                 // Row is narrower than the work area, no offset needed.
3071                 offset = 0;
3072         } else {
3073                 if (cur_x - offset < MARGIN) {
3074                         // cursor would be too far right
3075                         offset = cur_x - MARGIN;
3076                 } else if (cur_x - offset > workWidth() - MARGIN) {
3077                         // cursor would be too far left
3078                         offset = cur_x - workWidth() + MARGIN;
3079                 }
3080                 // Correct the offset to make sure that we do not scroll too much
3081                 if (offset < 0)
3082                         offset = 0;
3083                 if (row.right_x() - offset < workWidth() - row.right_margin)
3084                         offset = row.right_x() - workWidth() + row.right_margin;
3085         }
3086
3087         //lyxerr << "cur_x=" << cur_x << ", offset=" << offset << ", row.wid=" << row.width() << ", margin=" << MARGIN << endl;
3088
3089         if (offset != d->horiz_scroll_offset_)
3090                 LYXERR(Debug::PAINTING, "Horiz. scroll offset changed from "
3091                        << d->horiz_scroll_offset_ << " to " << offset);
3092
3093         if (d->update_strategy_ == NoScreenUpdate
3094             && (offset != d->horiz_scroll_offset_
3095                 || !d->last_row_slice_.empty())) {
3096                 // FIXME: if one uses SingleParUpdate, then home/end
3097                 // will not work on long rows. Why?
3098                 d->update_strategy_ = FullScreenUpdate;
3099         }
3100
3101         d->horiz_scroll_offset_ = offset;
3102 }
3103
3104
3105 void BufferView::draw(frontend::Painter & pain, bool paint_caret)
3106 {
3107         if (height_ == 0 || width_ == 0)
3108                 return;
3109         LYXERR(Debug::PAINTING, (pain.isNull() ? "\t\t--- START NODRAW ---"
3110                                  : "\t\t*** START DRAWING ***"));
3111         Text & text = buffer_.text();
3112         TextMetrics const & tm = d->text_metrics_[&text];
3113         int const y = tm.first().second->position();
3114         PainterInfo pi(this, pain);
3115
3116         /**  A repaint of the previous caret row is needed if there is
3117          *  caret painted on screen and either
3118          *   1/ a new caret has to be painted at a place different from
3119          *      the existing one;
3120          *   2/ there is no need for a caret anymore.
3121          */
3122         d->repaint_caret_row_ = !d->caret_slice_.empty() &&
3123                 ((paint_caret && d->cursor_.top() != d->caret_slice_)
3124                  || ! paint_caret);
3125
3126         // Check whether the row where the cursor lives needs to be scrolled.
3127         // Update the drawing strategy if needed.
3128         checkCursorScrollOffset();
3129
3130         switch (d->update_strategy_) {
3131
3132         case NoScreenUpdate:
3133                 // no screen painting is actually needed. In nodraw stage
3134                 // however, the different coordinates of insets and paragraphs
3135                 // needs to be updated.
3136                 LYXERR(Debug::PAINTING, "Strategy: NoScreenUpdate");
3137                 pi.full_repaint = false;
3138                 if (pain.isNull()) {
3139                         pi.full_repaint = true;
3140                         tm.draw(pi, 0, y);
3141                 } else if (d->repaint_caret_row_) {
3142                         pi.full_repaint = false;
3143                         tm.draw(pi, 0, y);
3144                 }
3145                 break;
3146
3147         case SingleParUpdate:
3148                 pi.full_repaint = false;
3149                 LYXERR(Debug::PAINTING, "Strategy: SingleParUpdate");
3150                 // In general, only the current row of the outermost paragraph
3151                 // will be redrawn. Particular cases where selection spans
3152                 // multiple paragraph are correctly detected in TextMetrics.
3153                 tm.draw(pi, 0, y);
3154                 break;
3155
3156         case DecorationUpdate:
3157                 // FIXME: We should also distinguish DecorationUpdate to avoid text
3158                 // drawing if possible. This is not possible to do easily right now
3159                 // because of the single backing pixmap.
3160
3161         case FullScreenUpdate:
3162
3163                 LYXERR(Debug::PAINTING,
3164                        ((d->update_strategy_ == FullScreenUpdate)
3165                         ? "Strategy: FullScreenUpdate"
3166                         : "Strategy: DecorationUpdate"));
3167
3168                 // The whole screen, including insets, will be refreshed.
3169                 pi.full_repaint = true;
3170
3171                 // Clear background.
3172                 pain.fillRectangle(0, 0, width_, height_,
3173                         pi.backgroundColor(&buffer_.inset()));
3174
3175                 // Draw everything.
3176                 tm.draw(pi, 0, y);
3177
3178                 // and possibly grey out below
3179                 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3180                 int const y2 = lastpm.second->position() + lastpm.second->descent();
3181
3182                 if (y2 < height_) {
3183                         Color color = buffer().isInternal()
3184                                 ? Color_background : Color_bottomarea;
3185                         pain.fillRectangle(0, y2, width_, height_ - y2, color);
3186                 }
3187                 break;
3188         }
3189         LYXERR(Debug::PAINTING, (pain.isNull() ? "\t\t --- END NODRAW ---"
3190                                 : "\t\t *** END DRAWING ***"));
3191
3192         // The scrollbar needs an update.
3193         updateScrollbar();
3194
3195         // Normalize anchor for next time
3196         pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
3197         pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3198         for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
3199                 ParagraphMetrics const & pm = tm.parMetrics(pit);
3200                 if (pm.position() + pm.descent() > 0) {
3201                         if (d->anchor_pit_ != pit
3202                             || d->anchor_ypos_ != pm.position())
3203                                 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
3204                                        << "  anchor ypos = " << d->anchor_ypos_);
3205                         d->anchor_pit_ = pit;
3206                         d->anchor_ypos_ = pm.position();
3207                         break;
3208                 }
3209         }
3210         if (!pain.isNull()) {
3211                 // reset the update flags, everything has been done
3212                 d->update_flags_ = Update::None;
3213         }
3214
3215         // Remember what has just been done for the next draw() step
3216         if (paint_caret) {
3217                 d->caret_slice_ = d->cursor_.top();
3218                 if (d->caret_slice_.pos() > 0
3219                     && (d->cursor_.boundary()
3220                         || d->caret_slice_.pos() == d->caret_slice_.lastpos()))
3221                         --d->caret_slice_.pos();
3222         } else
3223                 d->caret_slice_ = CursorSlice();
3224 }
3225
3226
3227 void BufferView::message(docstring const & msg)
3228 {
3229         if (d->gui_)
3230                 d->gui_->message(msg);
3231 }
3232
3233
3234 void BufferView::showDialog(string const & name)
3235 {
3236         if (d->gui_)
3237                 d->gui_->showDialog(name, string());
3238 }
3239
3240
3241 void BufferView::showDialog(string const & name,
3242         string const & data, Inset * inset)
3243 {
3244         if (d->gui_)
3245                 d->gui_->showDialog(name, data, inset);
3246 }
3247
3248
3249 void BufferView::updateDialog(string const & name, string const & data)
3250 {
3251         if (d->gui_)
3252                 d->gui_->updateDialog(name, data);
3253 }
3254
3255
3256 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
3257 {
3258         d->gui_ = gui;
3259 }
3260
3261
3262 // FIXME: Move this out of BufferView again
3263 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
3264 {
3265         if (!fname.isReadableFile()) {
3266                 docstring const error = from_ascii(strerror(errno));
3267                 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3268                 docstring const text =
3269                   bformat(_("Could not read the specified document\n"
3270                             "%1$s\ndue to the error: %2$s"), file, error);
3271                 Alert::error(_("Could not read file"), text);
3272                 return docstring();
3273         }
3274
3275         if (!fname.isReadableFile()) {
3276                 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3277                 docstring const text =
3278                   bformat(_("%1$s\n is not readable."), file);
3279                 Alert::error(_("Could not open file"), text);
3280                 return docstring();
3281         }
3282
3283         // FIXME UNICODE: We don't know the encoding of the file
3284         docstring file_content = fname.fileContents("UTF-8");
3285         if (file_content.empty()) {
3286                 Alert::error(_("Reading not UTF-8 encoded file"),
3287                              _("The file is not UTF-8 encoded.\n"
3288                                "It will be read as local 8Bit-encoded.\n"
3289                                "If this does not give the correct result\n"
3290                                "then please change the encoding of the file\n"
3291                                "to UTF-8 with a program other than LyX.\n"));
3292                 file_content = fname.fileContents("local8bit");
3293         }
3294
3295         return normalize_c(file_content);
3296 }
3297
3298
3299 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
3300 {
3301         docstring const tmpstr = contentsOfPlaintextFile(f);
3302
3303         if (tmpstr.empty())
3304                 return;
3305
3306         Cursor & cur = cursor();
3307         cap::replaceSelection(cur);
3308         buffer_.undo().recordUndo(cur);
3309         if (asParagraph)
3310                 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
3311         else
3312                 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
3313
3314         buffer_.changed(true);
3315 }
3316
3317
3318 docstring const & BufferView::inlineCompletion() const
3319 {
3320         return d->inlineCompletion_;
3321 }
3322
3323
3324 size_t const & BufferView::inlineCompletionUniqueChars() const
3325 {
3326         return d->inlineCompletionUniqueChars_;
3327 }
3328
3329
3330 DocIterator const & BufferView::inlineCompletionPos() const
3331 {
3332         return d->inlineCompletionPos_;
3333 }
3334
3335
3336 void BufferView::resetInlineCompletionPos()
3337 {
3338         d->inlineCompletionPos_ = DocIterator();
3339 }
3340
3341
3342 bool samePar(DocIterator const & a, DocIterator const & b)
3343 {
3344         if (a.empty() && b.empty())
3345                 return true;
3346         if (a.empty() || b.empty())
3347                 return false;
3348         if (a.depth() != b.depth())
3349                 return false;
3350         return &a.innerParagraph() == &b.innerParagraph();
3351 }
3352
3353
3354 void BufferView::setInlineCompletion(Cursor const & cur, DocIterator const & pos,
3355         docstring const & completion, size_t uniqueChars)
3356 {
3357         uniqueChars = min(completion.size(), uniqueChars);
3358         bool changed = d->inlineCompletion_ != completion
3359                 || d->inlineCompletionUniqueChars_ != uniqueChars;
3360         bool singlePar = true;
3361         d->inlineCompletion_ = completion;
3362         d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
3363
3364         //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
3365
3366         // at new position?
3367         DocIterator const & old = d->inlineCompletionPos_;
3368         if (old != pos) {
3369                 //lyxerr << "inlineCompletionPos changed" << std::endl;
3370                 // old or pos are in another paragraph?
3371                 if ((!samePar(cur, pos) && !pos.empty())
3372                     || (!samePar(cur, old) && !old.empty())) {
3373                         singlePar = false;
3374                         //lyxerr << "different paragraph" << std::endl;
3375                 }
3376                 d->inlineCompletionPos_ = pos;
3377         }
3378
3379         // set update flags
3380         if (changed) {
3381                 if (singlePar && !(cur.result().screenUpdate() & Update::Force))
3382                         cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
3383                 else
3384                         cur.screenUpdateFlags(cur.result().screenUpdate() | Update::Force);
3385         }
3386 }
3387
3388
3389 bool BufferView::clickableInset() const
3390 {
3391         return d->clickable_inset_;
3392 }
3393
3394 } // namespace lyx