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