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