3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alfredo Braunstein
7 * \author Lars Gullik Bjønnes
10 * \author Jürgen Vigna
12 * Full author contact details are available in file CREDITS.
17 #include "BufferView.h"
19 #include "BranchList.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "CoordCache.h"
25 #include "CutAndPaste.h"
26 #include "DispatchResult.h"
27 #include "ErrorList.h"
28 #include "FuncRequest.h"
29 #include "FuncStatus.h"
32 #include "LayoutFile.h"
35 #include "LyXAction.h"
38 #include "MetricsInfo.h"
39 #include "Paragraph.h"
42 #include "TextMetrics.h"
44 #include "TocBackend.h"
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"
53 #include "mathed/InsetMathNest.h"
54 #include "mathed/InsetMathRef.h"
55 #include "mathed/MathData.h"
56 #include "mathed/MathRow.h"
58 #include "frontends/alert.h"
59 #include "frontends/CaretGeometry.h"
60 #include "frontends/Delegates.h"
61 #include "frontends/FontMetrics.h"
62 #include "frontends/NullPainter.h"
63 #include "frontends/Painter.h"
64 #include "frontends/Selection.h"
65 #include "frontends/Clipboard.h"
67 #include "support/convert.h"
68 #include "support/debug.h"
69 #include "support/docstring.h"
70 #include "support/filetools.h"
71 #include "support/gettext.h"
72 #include "support/lassert.h"
73 #include "support/Length.h"
74 #include "support/lstrings.h"
75 #include "support/lyxlib.h"
76 #include "support/types.h"
88 using namespace lyx::support;
92 namespace Alert = frontend::Alert;
96 /// Return an inset of this class if it exists at the current cursor position
98 T * getInsetByCode(Cursor const & cur, InsetCode code)
100 DocIterator it = cur;
101 Inset * inset = it.nextInset();
102 if (inset && inset->lyxCode() == code)
103 return static_cast<T*>(inset);
108 /// Note that comparing contents can only be used for InsetCommand
109 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
110 docstring const & contents)
112 DocIterator tmpdit = dit;
115 Inset const * inset = tmpdit.nextInset();
117 bool const valid_code = std::find(codes.begin(), codes.end(),
118 inset->lyxCode()) != codes.end();
119 InsetCommand const * ic = inset->asInsetCommand();
120 bool const same_or_no_contents = contents.empty()
121 || (ic && (ic->getFirstNonOptParam() == contents));
123 if (valid_code && same_or_no_contents) {
128 tmpdit.forwardInset();
135 /// Looks for next inset with one of the given codes.
136 /// Note that same_content can only be used for InsetCommand
137 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
141 DocIterator tmpdit = dit;
142 tmpdit.forwardInset();
146 Inset const * inset = tmpdit.nextInset();
147 if (same_content && inset) {
148 InsetCommand const * ic = inset->asInsetCommand();
150 bool const valid_code = std::find(codes.begin(), codes.end(),
151 ic->lyxCode()) != codes.end();
153 contents = ic->getFirstNonOptParam();
157 if (!findNextInset(tmpdit, codes, contents)) {
158 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
159 inset = &tmpdit.bottom().inset();
160 tmpdit = doc_iterator_begin(&inset->buffer(), inset);
161 if (!findNextInset(tmpdit, codes, contents))
173 /// Moves cursor to the next inset with one of the given codes.
174 bool gotoInset(BufferView * bv, vector<InsetCode> const & codes,
177 Cursor tmpcur = bv->cursor();
178 if (!findInset(tmpcur, codes, same_content)) {
179 bv->cursor().message(_("No more insets"));
183 tmpcur.clearSelection();
184 bv->setCursor(tmpcur);
185 return bv->scrollToCursor(bv->cursor(), false, true);
189 /// A map from a Text to the associated text metrics
190 typedef map<Text const *, TextMetrics> TextMetricsCache;
192 enum ScreenUpdateStrategy {
202 /////////////////////////////////////////////////////////////////////
206 /////////////////////////////////////////////////////////////////////
208 struct BufferView::Private
210 Private(BufferView & bv) :
211 update_strategy_(FullScreenUpdate),
212 update_flags_(Update::Force),
213 cursor_(bv), anchor_pit_(0), anchor_ypos_(0),
214 wh_(0), inlineCompletionUniqueChars_(0),
215 last_inset_(nullptr), mouse_position_cache_(),
216 gui_(nullptr), bookmark_edit_position_(-1),
217 horiz_scroll_offset_(0), clickable_inset_(false)
219 xsel_cache_.set = false;
223 ScrollbarParameters scrollbarParameters_;
225 ScreenUpdateStrategy update_strategy_;
227 Update::flags update_flags_;
229 CoordCache coord_cache_;
231 typedef unordered_map<MathData const *, MathRow> MathRows;
234 /// this is used to handle XSelection events in the right manner.
243 pit_type anchor_pit_;
246 /// Estimated average par height for scrollbar.
249 vector<int> par_height_;
252 DocIterator inlineCompletionPos_;
254 docstring inlineCompletion_;
256 size_t inlineCompletionUniqueChars_;
258 /// keyboard mapping object.
261 /// last visited inset.
262 /** kept to send setMouseHover(false).
263 * Not owned, so don't delete.
265 Inset const * last_inset_;
267 /// position of the mouse at the time of the last mouse move
268 /// This is used to update the hovering status of inset in
269 /// cases where the buffer is scrolled, but the mouse didn't move.
270 Point mouse_position_cache_;
272 mutable TextMetricsCache text_metrics_;
275 /** Not owned, so don't delete.
277 frontend::GuiBufferViewDelegate * gui_;
280 map<string, Inset *> edited_insets_;
282 /// When the row where the cursor lies is scrolled, this
283 /// contains the scroll offset
284 // cache for id of the paragraph which was edited the last time
285 int bookmark_edit_position_;
287 int horiz_scroll_offset_;
288 /// a slice pointing to the start of the row where the cursor
289 /// is (at last draw time)
290 CursorSlice current_row_slice_;
291 /// are we hovering something that we can click
292 bool clickable_inset_;
293 /// shape of the caret
294 frontend::CaretGeometry caret_geometry_;
296 bool mouse_selecting_ = false;
300 BufferView::BufferView(Buffer & buf)
301 : width_(0), height_(0), full_screen_(false), buffer_(buf),
302 d(new Private(*this))
304 d->xsel_cache_.set = false;
305 d->intl_.initKeyMapper(lyxrc.use_kbmap);
307 d->cursor_.setBuffer(&buf);
308 d->cursor_.push(buffer_.inset());
309 d->cursor_.resetAnchor();
310 d->cursor_.setCurrentFont();
312 buffer_.updatePreviews();
316 BufferView::~BufferView()
318 // current buffer is going to be switched-off, save cursor pos
319 // Ideally, the whole cursor stack should be saved, but session
320 // currently can only handle bottom (whole document) level pit and pos.
321 // That is to say, if a cursor is in a nested inset, it will be
322 // restore to the left of the top level inset.
323 LastFilePosSection::FilePos fp;
324 fp.file = buffer_.fileName();
325 fp.pit = d->cursor_.bottom().pit();
326 fp.pos = d->cursor_.bottom().pos();
327 theSession().lastFilePos().save(fp);
330 d->last_inset_->setMouseHover(this, false);
336 int BufferView::defaultMargin() const
338 // The value used to be hardcoded to 10
339 return zoomedPixels(20);
343 int BufferView::rightMargin() const
345 // The additional test for the case the outliner is opened.
346 if (full_screen_ && lyxrc.full_screen_limit)
347 return max(defaultMargin(), (width_ - lyxrc.full_screen_width) / 2);
349 return defaultMargin();
353 int BufferView::leftMargin() const
355 return rightMargin();
359 int BufferView::topMargin() const
361 // Original value was 20px at 100dpi. For internal buffers like in
362 // advanced search and replace, a value of 5px is enough.
363 return zoomedPixels(buffer().isInternal() ? 5 : 20);
367 int BufferView::bottomMargin() const
373 int BufferView::inPixels(Length const & len) const
375 Font const font = buffer().params().getFont();
376 return len.inPixels(workWidth(), theFontMetrics(font).em());
380 int BufferView::zoomedPixels(int pix) const
382 // FIXME: the dpi setting should really depend on the BufferView
383 // (think different monitors).
385 // Zoom factor specified by user in percent
386 double const zoom = lyxrc.currentZoom / 100.0; // [percent]
388 // DPI setting for monitor relative to 100dpi
389 double const dpizoom = lyxrc.dpi / 100.0; // [per 100dpi]
391 return support::iround(pix * zoom * dpizoom);
395 bool BufferView::isTopScreen() const
397 return 0 == d->scrollbarParameters_.min;
401 bool BufferView::isBottomScreen() const
403 return 0 == d->scrollbarParameters_.max;
407 Intl & BufferView::getIntl()
413 Intl const & BufferView::getIntl() const
419 CoordCache & BufferView::coordCache()
421 return d->coord_cache_;
425 CoordCache const & BufferView::coordCache() const
427 return d->coord_cache_;
431 MathRow const & BufferView::mathRow(MathData const * cell) const
433 auto it = d->math_rows_.find(cell);
434 LATTEST(it != d->math_rows_.end());
439 void BufferView::setMathRow(MathData const * cell, MathRow const & mrow)
441 d->math_rows_[cell] = mrow;
445 Buffer & BufferView::buffer()
451 Buffer const & BufferView::buffer() const
457 docstring const & BufferView::searchRequestCache() const
459 return theClipboard().getFindBuffer();
463 void BufferView::setSearchRequestCache(docstring const & text)
471 docstring const search = string2find(text, casesensitive, matchword,
472 forward, wrap, instant, onlysel);
473 theClipboard().setFindBuffer(search);
477 bool BufferView::needsFitCursor() const
479 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
480 frontend::FontMetrics const & fm =
481 theFontMetrics(d->cursor_.getFont().fontInfo());
482 int const asc = fm.maxAscent();
483 int const des = fm.maxDescent();
484 Point const p = getPos(d->cursor_);
485 if (p.y_ - asc >= 0 && p.y_ + des < height_)
494 // this is for debugging only.
495 string flagsAsString(Update::flags flags)
497 if (flags == Update::None)
499 return string((flags & Update::FitCursor) ? "FitCursor " : "")
500 + ((flags & Update::Force) ? "Force " : "")
501 + ((flags & Update::ForceDraw) ? "ForceDraw " : "")
502 + ((flags & Update::SinglePar) ? "SinglePar " : "")
503 + ((flags & Update::Decoration) ? "Decoration " : "");
508 void BufferView::processUpdateFlags(Update::flags flags)
510 LYXERR(Debug::PAINTING, "BufferView::processUpdateFlags( "
511 << flagsAsString(flags) << ") buffer: " << &buffer_);
513 // Case when no explicit update is requested.
514 if (flags == Update::None)
517 /* FIXME We would like to avoid doing this here, since it is very
518 * expensive and is called in updateBuffer already. However, even
519 * inserting a plain character can invalidate the overly fragile
520 * tables of child documents built by updateMacros. Some work is
521 * needed to avoid doing that when not necessary.
523 buffer_.updateMacros();
525 // First check whether the metrics and inset positions should be updated
526 if (flags & Update::Force) {
527 // This will update the CoordCache items and replace Force
528 // with ForceDraw in flags.
529 updateMetrics(flags);
532 // Detect whether we can only repaint a single paragraph (if we
533 // are not already redrawing all).
534 // We handle this before FitCursor because the later will require
535 // correct metrics at cursor position.
536 if (!(flags & Update::ForceDraw)
537 && (flags & Update::SinglePar)
538 && !singleParUpdate())
539 updateMetrics(flags);
541 // Then make sure that the screen contains the cursor if needed
542 if (flags & Update::FitCursor) {
543 if (needsFitCursor()) {
544 // First try to make the selection start visible
545 // (which is just the cursor when there is no selection)
546 scrollToCursor(d->cursor_.selectionBegin(), false, false);
547 // Metrics have to be recomputed (maybe again)
549 // Is the cursor visible? (only useful if cursor is at end of selection)
550 if (needsFitCursor()) {
551 // then try to make cursor visible instead
552 scrollToCursor(d->cursor_, false, false);
553 // Metrics have to be recomputed (maybe again)
554 updateMetrics(flags);
557 flags = flags & ~Update::FitCursor;
560 // Add flags to the the update flags. These will be reset to None
561 // after the redraw is actually done
562 d->update_flags_ = d->update_flags_ | flags;
563 LYXERR(Debug::PAINTING, "Cumulative flags: " << flagsAsString(flags));
565 // Now compute the update strategy
566 // Possibly values in flag are None, SinglePar, Decoration, ForceDraw
567 LATTEST((d->update_flags_ & ~(Update::None | Update::SinglePar
568 | Update::Decoration | Update::ForceDraw)) == 0);
570 if (d->update_flags_ & Update::ForceDraw)
571 d->update_strategy_ = FullScreenUpdate;
572 else if (d->update_flags_ & Update::Decoration)
573 d->update_strategy_ = DecorationUpdate;
574 else if (d->update_flags_ & Update::SinglePar)
575 d->update_strategy_ = SingleParUpdate;
577 // no need to redraw anything.
578 d->update_strategy_ = NoScreenUpdate;
581 updateHoveredInset();
584 buffer_.changed(false);
588 void BufferView::updateScrollbarParameters()
590 if (height_ == 0 && width_ == 0)
593 // We prefer fixed size line scrolling.
594 d->scrollbarParameters_.single_step = defaultRowHeight();
595 // We prefer full screen page scrolling.
596 d->scrollbarParameters_.page_step = height_;
598 Text & t = buffer_.text();
599 TextMetrics & tm = d->text_metrics_[&t];
601 LYXERR(Debug::GUI, " Updating scrollbar: height: "
602 << t.paragraphs().size()
603 << " curr par: " << d->cursor_.bottom().pit()
604 << " default height " << defaultRowHeight());
606 size_t const parsize = t.paragraphs().size();
607 if (d->par_height_.size() != parsize) {
608 d->par_height_.clear();
609 // FIXME: We assume a default paragraph height of 2 rows. This
610 // should probably be pondered with the screen width.
611 d->par_height_.resize(parsize, defaultRowHeight() * 2);
614 // Look at paragraph heights on-screen
615 pair<pit_type, ParagraphMetrics const *> first = tm.first();
616 pair<pit_type, ParagraphMetrics const *> last = tm.last();
617 for (pit_type pit = first.first; pit <= last.first; ++pit) {
618 d->par_height_[pit] = tm.parMetrics(pit).height();
619 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
620 << d->par_height_[pit]);
623 int top_pos = first.second->position() - first.second->ascent();
624 int bottom_pos = last.second->position() + last.second->descent();
625 bool first_visible = first.first == 0 && top_pos >= 0;
626 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
627 if (first_visible && last_visible) {
628 d->scrollbarParameters_.min = 0;
629 d->scrollbarParameters_.max = 0;
633 d->scrollbarParameters_.min = top_pos;
634 for (size_t i = 0; i != size_t(first.first); ++i)
635 d->scrollbarParameters_.min -= d->par_height_[i];
636 d->scrollbarParameters_.max = bottom_pos;
637 for (size_t i = last.first + 1; i != parsize; ++i)
638 d->scrollbarParameters_.max += d->par_height_[i];
640 // The reference is the top position so we remove one page.
641 if (lyxrc.scroll_below_document)
642 d->scrollbarParameters_.max -= minVisiblePart();
644 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
646 // 0 must be inside the range as it denotes the current position
647 if (d->scrollbarParameters_.max < 0)
648 d->scrollbarParameters_.max = 0;
649 if (d->scrollbarParameters_.min > 0)
650 d->scrollbarParameters_.min = 0;
654 ScrollbarParameters const & BufferView::scrollbarParameters() const
656 return d->scrollbarParameters_;
660 docstring BufferView::toolTip(int x, int y) const
662 // Get inset under mouse, if there is one.
663 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
665 // No inset, no tooltip...
667 return covering_inset->toolTip(*this, x, y);
671 string BufferView::contextMenu(int x, int y) const
673 //If there is a selection, return the containing inset menu
674 if (d->cursor_.selection())
675 return d->cursor_.inset().contextMenu(*this, x, y);
677 // Get inset under mouse, if there is one.
678 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
679 if (covering_inset) {
680 if (covering_inset->asInsetMath()) {
681 CoordCache::Insets const & inset_cache =
682 coordCache().getInsets();
683 Inset const * inner_inset = mathContextMenu(
684 covering_inset->asInsetMath()->asNestInset(),
687 return inner_inset->contextMenu(*this, x, y);
689 return covering_inset->contextMenu(*this, x, y);
692 return buffer_.inset().contextMenu(*this, x, y);
696 Inset const * BufferView::mathContextMenu(InsetMathNest const * inset,
697 CoordCache::Insets const & inset_cache, int x, int y) const
699 for (size_t i = 0; i < inset->nargs(); ++i) {
700 MathData const & ar = inset->cell(i);
701 for (size_t j = 0; j < ar.size(); ++j) {
702 string const name = lyxerr.debugging(Debug::MATHED)
703 ? insetName(ar[j].nucleus()->lyxCode())
705 LYXERR(Debug::MATHED, "Examining inset: " << name);
706 if (!ar[j].nucleus()->contextMenuName().empty()) {
707 if (inset_cache.covers(ar[j].nucleus(), x, y)) {
708 LYXERR(Debug::MATHED, "Hit inset: "
710 return ar[j].nucleus();
713 InsetMathNest const * imn =
714 ar[j].nucleus()->asNestInset();
716 Inset const * inner =
717 mathContextMenu(imn, inset_cache, x, y);
727 void BufferView::scrollDocView(int const pixels, bool update)
729 // The scrollbar values are relative to the top of the screen, therefore the
730 // offset is equal to the target value.
732 // No scrolling at all? No need to redraw anything
736 // If the offset is less than 2 screen height, prefer to scroll instead.
737 if (abs(pixels) <= 2 * height_) {
738 d->anchor_ypos_ -= pixels;
739 processUpdateFlags(Update::Force);
743 // cut off at the top
744 if (pixels <= d->scrollbarParameters_.min) {
745 DocIterator dit = doc_iterator_begin(&buffer_);
746 showCursor(dit, false, false, update);
747 LYXERR(Debug::SCROLLING, "scroll to top");
751 // cut off at the bottom
752 if (pixels >= d->scrollbarParameters_.max) {
753 DocIterator dit = doc_iterator_end(&buffer_);
755 showCursor(dit, false, false, update);
756 LYXERR(Debug::SCROLLING, "scroll to bottom");
760 // find paragraph at target position
761 int par_pos = d->scrollbarParameters_.min;
763 for (; i != int(d->par_height_.size()); ++i) {
764 par_pos += d->par_height_[i];
765 if (par_pos >= pixels)
769 if (par_pos < pixels) {
770 // It seems we didn't find the correct pit so stay on the safe side and
772 LYXERR0("scrolling position not found!");
773 scrollDocView(d->scrollbarParameters_.max, update);
777 DocIterator dit = doc_iterator_begin(&buffer_);
779 LYXERR(Debug::SCROLLING, "pixels = " << pixels << " -> scroll to pit " << i);
780 showCursor(dit, false, false, update);
784 // FIXME: this method is not working well.
785 void BufferView::setCursorFromScrollbar()
787 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
789 int const height = 2 * defaultRowHeight();
790 int const first = height;
791 int const last = height_ - height;
793 Cursor const & oldcur = d->cursor_;
795 switch (cursorStatus(oldcur)) {
803 int const y = getPos(oldcur).y_;
804 newy = min(last, max(y, first));
808 // We reset the cursor because cursorStatus() does not
809 // work when the cursor is within mathed.
812 tm.setCursorFromCoordinates(cur, 0, newy);
814 // update the bufferview cursor and notify insets
815 // FIXME: Care about the d->cursor_ flags to redraw if needed
816 Cursor old = d->cursor_;
818 // the DEPM call in mouseSetCursor() might have destroyed the
819 // paragraph the cursor is in.
820 bool badcursor = old.fixIfBroken();
821 badcursor |= notifyCursorLeavesOrEnters(old, d->cursor_);
823 d->cursor_.fixIfBroken();
827 Change const BufferView::getCurrentChange() const
829 if (!d->cursor_.selection())
830 return Change(Change::UNCHANGED);
832 DocIterator dit = d->cursor_.selectionBegin();
833 // The selected content might have been changed (see #7685)
834 dit = dit.getInnerText();
835 return dit.paragraph().lookupChange(dit.pos());
839 // this could be used elsewhere as well?
840 // FIXME: This does not work within mathed!
841 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
843 Point const p = getPos(dit);
846 if (p.y_ > workHeight())
852 void BufferView::bookmarkEditPosition()
854 // Don't eat cpu time for each keystroke
855 if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
858 d->bookmark_edit_position_ = d->cursor_.paragraph().id();
862 void BufferView::saveBookmark(unsigned int idx)
864 if (buffer().isInternal())
867 // tentatively save bookmark, id and pos will be used to
868 // acturately locate a bookmark in a 'live' lyx session.
869 // pit and pos will be updated with bottom level pit/pos
871 theSession().bookmarks().save(
873 d->cursor_.bottom().pit(),
874 d->cursor_.bottom().pos(),
875 d->cursor_.paragraph().id(),
880 // emit message signal.
881 message(_("Save bookmark"));
885 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
886 int top_id, pos_type top_pos)
888 bool success = false;
891 d->cursor_.clearSelection();
893 // if a valid par_id is given, try it first
894 // This is the case for a 'live' bookmark when unique paragraph ID
895 // is used to track bookmarks.
897 dit = buffer_.getParFromID(top_id);
899 dit.pos() = min(dit.paragraph().size(), top_pos);
900 // Some slices of the iterator may not be
901 // reachable (e.g. closed collapsible inset)
902 // so the dociterator may need to be
903 // shortened. Otherwise, setCursor may crash
904 // lyx when the cursor can not be set to these
906 size_t const n = dit.depth();
907 for (size_t i = 0; i < n; ++i)
908 if (!dit[i].inset().editable()) {
916 // if top_id == 0, or searching through top_id failed
917 // This is the case for a 'restored' bookmark when only bottom
918 // (document level) pit was saved. Because of this, bookmark
919 // restoration is inaccurate. If a bookmark was within an inset,
920 // it will be restored to the left of the outmost inset that contains
922 if (!success && bottom_pit < int(buffer_.paragraphs().size())) {
923 dit = doc_iterator_begin(&buffer_);
925 dit.pit() = bottom_pit;
926 dit.pos() = min(bottom_pos, dit.paragraph().size());
931 // Note: only bottom (document) level pit is set.
933 // set the current font.
934 d->cursor_.setCurrentFont();
935 // Do not forget to reset the anchor (see #9912)
936 d->cursor_.resetAnchor();
937 processUpdateFlags(Update::Force | Update::FitCursor);
944 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
946 if (d->cursor_.real_current_font.isRightToLeft()) {
947 if (d->intl_.keymap == Intl::PRIMARY)
948 d->intl_.keyMapSec();
950 if (d->intl_.keymap == Intl::SECONDARY)
951 d->intl_.keyMapPrim();
954 d->intl_.getTransManager().translateAndInsert(c, t, cur);
958 int BufferView::workWidth() const
964 void BufferView::recenter()
966 showCursor(d->cursor_, true, false, true);
970 void BufferView::showCursor()
972 showCursor(d->cursor_, false, false, true);
976 void BufferView::showCursor(DocIterator const & dit,
977 bool recenter, bool force, bool update)
979 if (scrollToCursor(dit, recenter, force) && update)
980 processUpdateFlags(Update::Force);
984 bool BufferView::scrollToCursor(DocIterator const & dit, bool const recenter, bool force)
986 // We are not properly started yet, delay until resizing is done.
991 LYXERR(Debug::SCROLLING, "recentering and scrolling to cursor");
993 LYXERR(Debug::SCROLLING, "scrolling to cursor");
995 CursorSlice const & bot = dit.bottom();
996 TextMetrics & tm = textMetrics(bot.text());
998 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
999 pos_type bot_pit = bot.pit();
1000 if (bot_pit > max_pit) {
1001 // FIXME: Why does this happen?
1002 LYXERR0("bottom pit is greater that max pit: "
1003 << bot_pit << " > " << max_pit);
1007 if (bot_pit == tm.first().first - 1)
1008 tm.newParMetricsUp();
1009 else if (bot_pit == tm.last().first + 1)
1010 tm.newParMetricsDown();
1012 if (tm.contains(bot_pit) && !force) {
1013 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
1014 LBUFERR(!pm.rows().empty());
1015 // FIXME: smooth scrolling doesn't work in mathed.
1016 CursorSlice const & cs = dit.innerTextSlice();
1017 int const ypos = pm.position() + coordOffset(dit).y_;
1018 ParagraphMetrics const & inner_pm =
1019 textMetrics(cs.text()).parMetrics(cs.pit());
1020 Dimension const & row_dim =
1021 inner_pm.getRow(cs.pos(), dit.boundary()).dim();
1024 scrolled = scroll(ypos - height_/2);
1026 // We try to visualize the whole row, if the row height is larger than
1027 // the screen height, we scroll to a heuristic value of height_ / 4.
1028 // FIXME: This heuristic value should be replaced by a recursive search
1029 // for a row in the inset that can be visualized completely.
1030 else if (row_dim.height() > height_) {
1031 if (ypos < defaultRowHeight())
1032 scrolled = scroll(ypos - height_ / 4);
1033 else if (ypos > height_ - defaultRowHeight())
1034 scrolled = scroll(ypos - 3 * height_ / 4);
1037 // If the top part of the row falls of the screen, we scroll
1038 // up to align the top of the row with the top of the screen.
1039 else if (ypos - row_dim.ascent() < 0 && ypos < height_) {
1040 int const ynew = row_dim.ascent();
1041 scrolled = scrollUp(ynew - ypos);
1044 // If the bottom of the row falls of the screen, we scroll down.
1045 else if (ypos + row_dim.descent() > height_ && ypos > 0) {
1046 int const ynew = height_ - row_dim.descent();
1047 scrolled = scrollDown(ypos - ynew);
1050 // else, nothing to do, the cursor is already visible so we just return.
1051 return scrolled != 0;
1054 // fix inline completion position
1055 if (d->inlineCompletionPos_.fixIfBroken())
1056 d->inlineCompletionPos_ = DocIterator();
1058 tm.redoParagraph(bot_pit);
1059 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
1060 int const offset = coordOffset(dit).y_;
1062 d->anchor_pit_ = bot_pit;
1063 CursorSlice const & cs = dit.innerTextSlice();
1064 ParagraphMetrics const & inner_pm =
1065 textMetrics(cs.text()).parMetrics(cs.pit());
1066 Dimension const & row_dim =
1067 inner_pm.getRow(cs.pos(), dit.boundary()).dim();
1070 d->anchor_ypos_ = height_/2;
1071 else if (d->anchor_pit_ == 0)
1072 d->anchor_ypos_ = offset + pm.ascent();
1073 else if (d->anchor_pit_ == max_pit)
1074 d->anchor_ypos_ = height_ - offset - row_dim.descent();
1075 else if (offset > height_)
1076 d->anchor_ypos_ = height_ - offset - row_dim.descent();
1078 d->anchor_ypos_ = row_dim.ascent();
1084 void BufferView::makeDocumentClass()
1086 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
1087 buffer_.params().makeDocumentClass(buffer_.isClone(), buffer_.isInternal());
1088 updateDocumentClass(olddc);
1092 void BufferView::updateDocumentClass(DocumentClassConstPtr olddc)
1094 StableDocIterator backcur(d->cursor_);
1095 ErrorList & el = buffer_.errorList("Class Switch");
1096 cap::switchBetweenClasses(
1097 olddc, buffer_.params().documentClassPtr(),
1098 static_cast<InsetText &>(buffer_.inset()), el);
1100 setCursor(backcur.asDocIterator(&buffer_));
1102 buffer_.errors("Class Switch");
1106 /** Return the change status at cursor position, taking into account the
1107 * status at each level of the document iterator (a table in a deleted
1108 * footnote is deleted).
1109 * When \param outer is true, the top slice is not looked at.
1111 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
1113 size_t const depth = dit.depth() - (outer ? 1 : 0);
1115 for (size_t i = 0 ; i < depth ; ++i) {
1116 CursorSlice const & slice = dit[i];
1117 if (!slice.inset().inMathed()
1118 && slice.pos() < slice.paragraph().size()) {
1119 Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
1120 if (ch != Change::UNCHANGED)
1124 return Change::UNCHANGED;
1128 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1130 FuncCode const act = cmd.action();
1132 // Can we use a readonly buffer?
1133 if (buffer_.isReadonly()
1134 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1135 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1136 if (buffer_.hasReadonlyFlag())
1137 flag.message(from_utf8(N_("Document is read-only")));
1139 flag.message(from_utf8(N_("Document has been modified externally")));
1140 flag.setEnabled(false);
1144 // Are we in a DELETED change-tracking region?
1145 if (lookupChangeType(d->cursor_, true) == Change::DELETED
1146 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1147 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1148 flag.message(from_utf8(N_("This portion of the document is deleted.")));
1149 flag.setEnabled(false);
1153 Cursor & cur = d->cursor_;
1155 if (cur.getStatus(cmd, flag))
1160 // FIXME: This is a bit problematic because we don't check if this is
1161 // a document BufferView or not for these LFUNs. We probably have to
1162 // dispatch both to currentBufferView() and, if that fails,
1163 // to documentBufferView(); same as we do now for current Buffer and
1164 // document Buffer. Ideally those LFUN should go to Buffer as they
1165 // operate on the full Buffer and the cursor is only needed either for
1166 // an Undo record or to restore a cursor position. But we don't know
1167 // how to do that inside Buffer of course.
1168 case LFUN_BUFFER_PARAMS_APPLY:
1169 case LFUN_LAYOUT_MODULES_CLEAR:
1170 case LFUN_LAYOUT_MODULE_ADD:
1171 case LFUN_LAYOUT_RELOAD:
1172 case LFUN_TEXTCLASS_APPLY:
1173 case LFUN_TEXTCLASS_LOAD:
1174 flag.setEnabled(!buffer_.isReadonly());
1178 // We do not use the LyXAction flag for readonly because Undo sets the
1179 // buffer clean/dirty status by itself.
1180 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasUndoStack());
1183 // We do not use the LyXAction flag for readonly because Redo sets the
1184 // buffer clean/dirty status by itself.
1185 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasRedoStack());
1187 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1188 case LFUN_FILE_INSERT_PLAINTEXT: {
1189 docstring const & fname = cmd.argument();
1190 if (!FileName::isAbsolute(to_utf8(fname))) {
1191 flag.message(_("Absolute filename expected."));
1194 flag.setEnabled(cur.inTexted());
1197 case LFUN_FILE_INSERT:
1198 case LFUN_BOOKMARK_SAVE:
1199 // FIXME: Actually, these LFUNS should be moved to Text
1200 flag.setEnabled(cur.inTexted());
1203 case LFUN_FONT_STATE:
1204 case LFUN_LABEL_INSERT:
1205 case LFUN_INFO_INSERT:
1206 case LFUN_PARAGRAPH_GOTO:
1207 case LFUN_NOTE_NEXT:
1208 case LFUN_REFERENCE_NEXT:
1209 case LFUN_WORD_FIND:
1210 case LFUN_WORD_FIND_FORWARD:
1211 case LFUN_WORD_FIND_BACKWARD:
1212 case LFUN_WORD_REPLACE:
1215 case LFUN_MARK_TOGGLE:
1216 case LFUN_SEARCH_STRING_SET:
1217 case LFUN_SCREEN_RECENTER:
1218 case LFUN_SCREEN_SHOW_CURSOR:
1219 case LFUN_BIBTEX_DATABASE_ADD:
1220 case LFUN_BIBTEX_DATABASE_DEL:
1221 case LFUN_STATISTICS:
1222 case LFUN_KEYMAP_OFF:
1223 case LFUN_KEYMAP_PRIMARY:
1224 case LFUN_KEYMAP_SECONDARY:
1225 case LFUN_KEYMAP_TOGGLE:
1226 case LFUN_INSET_SELECT_ALL:
1227 flag.setEnabled(true);
1230 case LFUN_GRAPHICS_UNIFY:
1231 flag.setEnabled(cur.countInsetsInSelection(GRAPHICS_CODE)>1);
1234 case LFUN_WORD_FINDADV: {
1235 FindAndReplaceOptions opt;
1236 istringstream iss(to_utf8(cmd.argument()));
1238 flag.setEnabled(opt.repl_buf_name.empty()
1239 || !buffer_.isReadonly());
1243 case LFUN_LABEL_GOTO:
1244 flag.setEnabled(!cmd.argument().empty()
1245 || getInsetByCode<InsetRef>(cur, REF_CODE)
1246 || getInsetByCode<InsetMathRef>(cur, MATH_REF_CODE));
1249 case LFUN_CHANGES_MERGE:
1250 case LFUN_CHANGE_NEXT:
1251 case LFUN_CHANGE_PREVIOUS:
1252 case LFUN_ALL_CHANGES_ACCEPT:
1253 case LFUN_ALL_CHANGES_REJECT:
1254 flag.setEnabled(buffer_.areChangesPresent());
1257 case LFUN_SCREEN_UP:
1258 case LFUN_SCREEN_DOWN:
1260 case LFUN_SCREEN_UP_SELECT:
1261 case LFUN_SCREEN_DOWN_SELECT:
1262 case LFUN_INSET_FORALL:
1263 flag.setEnabled(true);
1266 case LFUN_LAYOUT_TABULAR:
1267 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1271 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1274 case LFUN_LAYOUT_PARAGRAPH:
1275 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1278 case LFUN_BRANCH_ADD_INSERT:
1279 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1282 case LFUN_DIALOG_SHOW_NEW_INSET:
1283 // FIXME: this is wrong, but I do not understand the
1285 if (cur.inset().lyxCode() == CAPTION_CODE)
1286 return cur.inset().getStatus(cur, cmd, flag);
1287 // FIXME we should consider passthru paragraphs too.
1288 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1291 case LFUN_CITATION_INSERT: {
1292 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1293 // FIXME: This could turn in a recursive hell.
1294 // Shouldn't we use Buffer::getStatus() instead?
1295 flag.setEnabled(lyx::getStatus(fr).enabled());
1298 case LFUN_INSET_APPLY: {
1299 string const name = cmd.getArg(0);
1300 Inset * inset = editedInset(name);
1302 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1303 if (!inset->getStatus(cur, fr, flag)) {
1304 // Every inset is supposed to handle this
1305 LASSERT(false, break);
1308 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1309 flag = lyx::getStatus(fr);
1315 flag.setEnabled(cur.selection());
1326 Inset * BufferView::editedInset(string const & name) const
1328 map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1329 return it == d->edited_insets_.end() ? nullptr : it->second;
1333 void BufferView::editInset(string const & name, Inset * inset)
1336 d->edited_insets_[name] = inset;
1338 d->edited_insets_.erase(name);
1342 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1344 LYXERR(Debug::ACTION, "BufferView::dispatch: cmd: " << cmd);
1346 string const argument = to_utf8(cmd.argument());
1347 Cursor & cur = d->cursor_;
1350 // Don't dispatch function that does not apply to internal buffers.
1351 if (buffer_.isInternal()
1352 && lyxaction.funcHasFlag(cmd.action(), LyXAction::NoInternal))
1355 // We'll set this back to false if need be.
1356 bool dispatched = true;
1357 buffer_.undo().beginUndoGroup();
1359 FuncCode const act = cmd.action();
1362 case LFUN_BUFFER_PARAMS_APPLY: {
1363 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
1364 cur.recordUndoBufferParams();
1365 istringstream ss(to_utf8(cmd.argument()));
1368 int const unknown_tokens = buffer_.readHeader(lex);
1369 if (unknown_tokens != 0) {
1370 LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1371 << unknown_tokens << " unknown token"
1372 << (unknown_tokens == 1 ? "" : "s"));
1374 updateDocumentClass(olddc);
1376 // We are most certainly here because of a change in the document
1377 // It is then better to make sure that all dialogs are in sync with
1378 // current document settings.
1379 dr.screenUpdate(Update::Force | Update::FitCursor);
1380 dr.forceBufferUpdate();
1384 case LFUN_LAYOUT_MODULES_CLEAR: {
1385 // FIXME: this modifies the document in cap::switchBetweenClasses
1386 // without calling recordUndo. Fix this before using
1387 // recordUndoBufferParams().
1388 cur.recordUndoFullBuffer();
1389 buffer_.params().clearLayoutModules();
1390 makeDocumentClass();
1391 dr.screenUpdate(Update::Force);
1392 dr.forceBufferUpdate();
1396 case LFUN_LAYOUT_MODULE_ADD: {
1397 BufferParams const & params = buffer_.params();
1398 if (!params.layoutModuleCanBeAdded(argument)) {
1399 LYXERR0("Module `" << argument <<
1400 "' cannot be added due to failed requirements or "
1401 "conflicts with installed modules.");
1404 // FIXME: this modifies the document in cap::switchBetweenClasses
1405 // without calling recordUndo. Fix this before using
1406 // recordUndoBufferParams().
1407 cur.recordUndoFullBuffer();
1408 buffer_.params().addLayoutModule(argument);
1409 makeDocumentClass();
1410 dr.screenUpdate(Update::Force);
1411 dr.forceBufferUpdate();
1415 case LFUN_TEXTCLASS_APPLY: {
1416 // since this shortcircuits, the second call is made only if
1418 bool const success =
1419 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1420 LayoutFileList::get().load(argument, buffer_.filePath());
1422 docstring s = bformat(_("The document class `%1$s' "
1423 "could not be loaded."), from_utf8(argument));
1424 frontend::Alert::error(_("Could not load class"), s);
1428 LayoutFile const * old_layout = buffer_.params().baseClass();
1429 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1431 if (old_layout == new_layout)
1435 // Save the old, possibly modular, layout for use in conversion.
1436 // FIXME: this modifies the document in cap::switchBetweenClasses
1437 // without calling recordUndo. Fix this before using
1438 // recordUndoBufferParams().
1439 cur.recordUndoFullBuffer();
1440 buffer_.params().setBaseClass(argument, buffer_.layoutPos());
1441 makeDocumentClass();
1442 dr.screenUpdate(Update::Force);
1443 dr.forceBufferUpdate();
1447 case LFUN_TEXTCLASS_LOAD: {
1448 // since this shortcircuits, the second call is made only if
1450 bool const success =
1451 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1452 LayoutFileList::get().load(argument, buffer_.filePath());
1454 docstring s = bformat(_("The document class `%1$s' "
1455 "could not be loaded."), from_utf8(argument));
1456 frontend::Alert::error(_("Could not load class"), s);
1461 case LFUN_LAYOUT_RELOAD: {
1462 LayoutFileIndex bc = buffer_.params().baseClassID();
1463 LayoutFileList::get().reset(bc);
1464 buffer_.params().setBaseClass(bc, buffer_.layoutPos());
1465 makeDocumentClass();
1466 dr.screenUpdate(Update::Force);
1467 dr.forceBufferUpdate();
1472 dr.setMessage(_("Undo"));
1473 cur.clearSelection();
1474 // We need to find out if the bibliography information
1475 // has changed. See bug #11055.
1476 // So these should not be references...
1477 string const engine = buffer().params().citeEngine();
1478 CiteEngineType const enginetype = buffer().params().citeEngineType();
1479 if (!cur.undoAction())
1480 dr.setMessage(_("No further undo information"));
1482 dr.screenUpdate(Update::Force | Update::FitCursor);
1483 dr.forceBufferUpdate();
1484 resetInlineCompletionPos();
1485 if (buffer().params().citeEngine() != engine ||
1486 buffer().params().citeEngineType() != enginetype)
1487 buffer().invalidateCiteLabels();
1493 dr.setMessage(_("Redo"));
1494 cur.clearSelection();
1495 // We need to find out if the bibliography information
1496 // has changed. See bug #11055.
1497 // So these should not be references...
1498 string const engine = buffer().params().citeEngine();
1499 CiteEngineType const enginetype = buffer().params().citeEngineType();
1500 if (!cur.redoAction())
1501 dr.setMessage(_("No further redo information"));
1503 dr.screenUpdate(Update::Force | Update::FitCursor);
1504 dr.forceBufferUpdate();
1505 resetInlineCompletionPos();
1506 if (buffer().params().citeEngine() != engine ||
1507 buffer().params().citeEngineType() != enginetype)
1508 buffer().invalidateCiteLabels();
1513 case LFUN_FONT_STATE:
1514 dr.setMessage(cur.currentState(false));
1517 case LFUN_BOOKMARK_SAVE:
1518 dr.screenUpdate(Update::Force);
1519 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1522 case LFUN_LABEL_GOTO: {
1523 docstring label = cmd.argument();
1524 if (label.empty()) {
1526 getInsetByCode<InsetRef>(cur, REF_CODE);
1528 label = inset->getParam("reference");
1529 // persistent=false: use temp_bookmark
1533 if (!label.empty()) {
1535 // at the moment, this is redundant, since gotoLabel will
1536 // eventually call LFUN_PARAGRAPH_GOTO, but it seems best
1538 dr.screenUpdate(Update::Force | Update::FitCursor);
1540 InsetMathRef * minset =
1541 getInsetByCode<InsetMathRef>(cur, MATH_REF_CODE);
1543 lyx::dispatch(FuncRequest(LFUN_LABEL_GOTO,
1544 minset->getTarget()));
1549 case LFUN_PARAGRAPH_GOTO: {
1550 int const id = convert<int>(cmd.getArg(0));
1551 pos_type const pos = convert<int>(cmd.getArg(1));
1554 string const str_id_end = cmd.getArg(2);
1555 string const str_pos_end = cmd.getArg(3);
1557 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1558 b = theBufferList().next(b)) {
1561 curs.setCursor(b->getParFromID(id));
1563 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1567 LYXERR(Debug::INFO, "Paragraph " << curs.paragraph().id()
1568 << " found in buffer `"
1569 << b->absFileName() << "'.");
1571 if (b == &buffer_) {
1573 if (str_id_end.empty() || str_pos_end.empty()) {
1576 mouseSetCursor(curs);
1579 int const id_end = convert<int>(str_id_end);
1580 pos_type const pos_end = convert<int>(str_pos_end);
1581 success = setCursorFromEntries({id, pos},
1584 if (success && scrollToCursor(d->cursor_, false, true))
1585 dr.screenUpdate(Update::Force);
1587 // Switch to other buffer view and resend cmd
1588 lyx::dispatch(FuncRequest(
1589 LFUN_BUFFER_SWITCH, b->absFileName()));
1597 case LFUN_NOTE_NEXT:
1598 if (gotoInset(this, { NOTE_CODE }, false))
1599 dr.screenUpdate(Update::Force);
1602 case LFUN_REFERENCE_NEXT: {
1603 if (gotoInset(this, { LABEL_CODE, REF_CODE }, true))
1604 dr.screenUpdate(Update::Force);
1608 case LFUN_CHANGE_NEXT:
1609 findNextChange(this);
1610 if (cur.inset().isTable())
1611 // In tables, there might be whole changed rows or columns
1613 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1614 dr.screenUpdate(Update::Force | Update::FitCursor);
1617 case LFUN_CHANGE_PREVIOUS:
1618 findPreviousChange(this);
1619 if (cur.inset().isTable())
1620 // In tables, there might be whole changed rows or columns
1622 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1623 dr.screenUpdate(Update::Force | Update::FitCursor);
1626 case LFUN_CHANGES_MERGE:
1627 if (findNextChange(this) || findPreviousChange(this)) {
1628 dr.screenUpdate(Update::Force | Update::FitCursor);
1629 dr.forceBufferUpdate();
1630 showDialog("changes");
1634 case LFUN_ALL_CHANGES_ACCEPT: {
1635 // select complete document
1637 cur.selHandle(true);
1638 buffer_.text().cursorBottom(cur);
1639 // accept everything in a single step to support atomic undo
1640 // temporarily disable track changes in order to end with really
1641 // no new (e.g., DPSM-caused) changes (see #7487)
1642 bool const track = buffer_.params().track_changes;
1643 buffer_.params().track_changes = false;
1644 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1645 buffer_.params().track_changes = track;
1647 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1648 dr.screenUpdate(Update::Force | Update::FitCursor);
1649 dr.forceBufferUpdate();
1653 case LFUN_ALL_CHANGES_REJECT: {
1654 // select complete document
1656 cur.selHandle(true);
1657 buffer_.text().cursorBottom(cur);
1658 // reject everything in a single step to support atomic undo
1659 // temporarily disable track changes in order to end with really
1660 // no new (e.g., DPSM-caused) changes (see #7487)
1661 bool const track = buffer_.params().track_changes;
1662 buffer_.params().track_changes = false;
1663 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1664 buffer_.params().track_changes = track;
1666 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1667 dr.screenUpdate(Update::Force | Update::FitCursor);
1668 dr.forceBufferUpdate();
1672 case LFUN_WORD_FIND_FORWARD:
1673 case LFUN_WORD_FIND_BACKWARD: {
1674 docstring searched_string;
1676 if (!cmd.argument().empty()) {
1677 setSearchRequestCache(cmd.argument());
1678 searched_string = cmd.argument();
1680 searched_string = searchRequestCache();
1683 if (searched_string.empty())
1686 docstring const data =
1687 find2string(searched_string, false, false,
1688 act == LFUN_WORD_FIND_FORWARD, false, false, false);
1689 bool found = lyxfind(this, FuncRequest(LFUN_WORD_FIND, data));
1691 dr.screenUpdate(Update::Force | Update::FitCursor);
1693 dr.setMessage(_("Search string not found!"));
1697 case LFUN_WORD_FIND: {
1698 docstring arg = cmd.argument();
1700 arg = searchRequestCache();
1702 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1705 if (lyxfind(this, FuncRequest(act, arg)))
1706 dr.screenUpdate(Update::Force | Update::FitCursor);
1708 dr.setMessage(_("Search string not found!"));
1710 setSearchRequestCache(arg);
1714 case LFUN_SEARCH_STRING_SET: {
1715 docstring pattern = cmd.argument();
1716 if (!pattern.empty()) {
1717 setSearchRequestCache(pattern);
1720 if (cur.selection())
1721 pattern = cur.selectionAsString(false);
1723 pos_type spos = cur.pos();
1724 cur.innerText()->selectWord(cur, WHOLE_WORD);
1725 pattern = cur.selectionAsString(false);
1726 cur.selection(false);
1729 setSearchRequestCache(pattern);
1733 case LFUN_WORD_REPLACE: {
1734 if (lyxreplace(this, cmd)) {
1735 dr.forceBufferUpdate();
1736 dr.screenUpdate(Update::Force | Update::FitCursor);
1739 dr.setMessage(_("Search string not found!"));
1743 case LFUN_WORD_FINDADV: {
1744 FindAndReplaceOptions opt;
1745 istringstream iss(to_utf8(cmd.argument()));
1747 if (findAdv(this, opt)) {
1748 dr.screenUpdate(Update::Force | Update::FitCursor);
1759 cur.clearSelection();
1760 dr.setMessage(from_utf8(N_("Mark off")));
1764 cur.clearSelection();
1766 dr.setMessage(from_utf8(N_("Mark on")));
1769 case LFUN_MARK_TOGGLE:
1770 cur.selection(false);
1773 dr.setMessage(from_utf8(N_("Mark removed")));
1776 dr.setMessage(from_utf8(N_("Mark set")));
1781 case LFUN_SCREEN_SHOW_CURSOR:
1785 case LFUN_SCREEN_RECENTER:
1789 case LFUN_BIBTEX_DATABASE_ADD: {
1790 Cursor tmpcur = cur;
1791 findInset(tmpcur, { BIBTEX_CODE }, false);
1792 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1795 if (inset->addDatabase(cmd.argument()))
1796 dr.forceBufferUpdate();
1801 case LFUN_BIBTEX_DATABASE_DEL: {
1802 Cursor tmpcur = cur;
1803 findInset(tmpcur, { BIBTEX_CODE }, false);
1804 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1807 if (inset->delDatabase(cmd.argument()))
1808 dr.forceBufferUpdate();
1813 case LFUN_GRAPHICS_UNIFY: {
1815 cur.recordUndoFullBuffer();
1817 DocIterator from, to;
1818 from = cur.selectionBegin();
1819 to = cur.selectionEnd();
1821 string const newId = cmd.getArg(0);
1822 bool fetchId = newId.empty(); //if we wait for groupId from first graphics inset
1824 InsetGraphicsParams grp_par;
1826 InsetGraphics::string2params(graphics::getGroupParams(buffer_, newId), buffer_, grp_par);
1828 if (!from.nextInset()) //move to closest inset
1829 from.forwardInset();
1831 while (!from.empty() && from < to) {
1832 Inset * inset = from.nextInset();
1835 InsetGraphics * ig = inset->asInsetGraphics();
1837 InsetGraphicsParams inspar = ig->getParams();
1842 grp_par.filename = inspar.filename;
1843 ig->setParams(grp_par);
1846 from.forwardInset();
1848 dr.screenUpdate(Update::Force); //needed if triggered from context menu
1852 case LFUN_STATISTICS: {
1853 DocIterator from, to;
1854 if (cur.selection()) {
1855 from = cur.selectionBegin();
1856 to = cur.selectionEnd();
1858 from = doc_iterator_begin(&buffer_);
1859 to = doc_iterator_end(&buffer_);
1861 buffer_.updateStatistics(from, to);
1862 int const words = buffer_.wordCount();
1863 int const chars = buffer_.charCount(false);
1864 int const chars_blanks = buffer_.charCount(true);
1866 if (cur.selection())
1867 message = _("Statistics for the selection:");
1869 message = _("Statistics for the document:");
1872 message += bformat(_("%1$d words"), words);
1874 message += _("One word");
1876 if (chars_blanks != 1)
1877 message += bformat(_("%1$d characters (including blanks)"),
1880 message += _("One character (including blanks)");
1883 message += bformat(_("%1$d characters (excluding blanks)"),
1886 message += _("One character (excluding blanks)");
1888 Alert::information(_("Statistics"), message);
1892 case LFUN_SCREEN_UP:
1893 case LFUN_SCREEN_DOWN: {
1894 Point p = getPos(cur);
1895 // This code has been commented out to enable to scroll down a
1896 // document, even if there are large insets in it (see bug #5465).
1897 /*if (p.y_ < 0 || p.y_ > height_) {
1898 // The cursor is off-screen so recenter before proceeding.
1902 int const scrolled = scroll(act == LFUN_SCREEN_UP
1903 ? -height_ : height_);
1904 if (act == LFUN_SCREEN_UP && scrolled > -height_)
1906 if (act == LFUN_SCREEN_DOWN && scrolled < height_)
1907 p = Point(width_, height_);
1908 bool const in_texted = cur.inTexted();
1909 cur.setCursor(doc_iterator_begin(cur.buffer()));
1910 cur.selHandle(false);
1911 // Force an immediate computation of metrics because we need it below
1913 processUpdateFlags(Update::Force);
1915 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1916 true, act == LFUN_SCREEN_UP);
1917 //FIXME: what to do with cur.x_target()?
1918 bool update = in_texted && cur.bv().checkDepm(cur, old);
1921 if (update || cur.mark())
1922 dr.screenUpdate(Update::Force | Update::FitCursor);
1924 dr.forceBufferUpdate();
1929 string const scroll_type = cmd.getArg(0);
1930 int scroll_step = 0;
1931 if (scroll_type == "line")
1932 scroll_step = d->scrollbarParameters_.single_step;
1933 else if (scroll_type == "page")
1934 scroll_step = d->scrollbarParameters_.page_step;
1937 string const scroll_quantity = cmd.getArg(1);
1938 if (scroll_quantity == "up")
1939 scrollUp(scroll_step);
1940 else if (scroll_quantity == "down")
1941 scrollDown(scroll_step);
1943 int const scroll_value = convert<int>(scroll_quantity);
1945 scroll(scroll_step * scroll_value);
1947 dr.screenUpdate(Update::ForceDraw);
1948 dr.forceBufferUpdate();
1952 case LFUN_SCREEN_UP_SELECT: {
1953 // FIXME: why is the algorithm different from LFUN_SCREEN_UP?
1954 cur.selHandle(true);
1955 if (isTopScreen()) {
1956 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1960 int y = getPos(cur).y_;
1961 int const ymin = y - height_ + defaultRowHeight();
1962 while (y > ymin && cur.up())
1966 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1970 case LFUN_SCREEN_DOWN_SELECT: {
1971 // FIXME: why is the algorithm different from LFUN_SCREEN_DOWN?
1972 cur.selHandle(true);
1973 if (isBottomScreen()) {
1974 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1978 int y = getPos(cur).y_;
1979 int const ymax = y + height_ - defaultRowHeight();
1980 while (y < ymax && cur.down())
1984 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1989 case LFUN_INSET_SELECT_ALL: {
1990 // true if all cells are selected
1991 bool const all_selected = cur.depth() > 1
1992 && cur.selBegin().at_begin()
1993 && cur.selEnd().at_end();
1994 // true if some cells are selected
1995 bool const cells_selected = cur.depth() > 1
1996 && cur.selBegin().at_cell_begin()
1997 && cur.selEnd().at_cell_end();
1998 if (all_selected || (cells_selected && !cur.inset().isTable())) {
1999 // All the contents of the inset if selected, or only at
2000 // least one cell but inset is not a table.
2001 // Select the inset from outside.
2004 cur.selection(true);
2006 } else if (cells_selected) {
2007 // At least one complete cell is selected and inset is a table.
2013 cur.selection(true);
2014 cur.idx() = cur.lastidx();
2015 cur.pit() = cur.lastpit();
2016 cur.pos() = cur.lastpos();
2018 // select current cell
2022 cur.selection(true);
2023 cur.pit() = cur.lastpit();
2024 cur.pos() = cur.lastpos();
2026 cur.setCurrentFont();
2027 dr.screenUpdate(Update::Force);
2032 case LFUN_UNICODE_INSERT: {
2033 if (cmd.argument().empty())
2036 FuncCode code = cur.inset().currentMode() == Inset::MATH_MODE ?
2037 LFUN_MATH_INSERT : LFUN_SELF_INSERT;
2040 docstring const arg = from_utf8(cmd.getArg(i));
2044 LYXERR0("Not a hexstring: " << arg);
2048 char_type c = hexToInt(arg);
2049 if (c >= 32 && c < 0x10ffff) {
2050 LYXERR(Debug::KEY, "Inserting c: " << c);
2051 lyx::dispatch(FuncRequest(code, docstring(1, c)));
2059 // This would be in Buffer class if only Cursor did not
2060 // require a bufferview
2061 case LFUN_INSET_FORALL: {
2062 docstring const name = from_utf8(cmd.getArg(0));
2063 string const commandstr = cmd.getLongArg(1);
2064 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
2066 // an arbitrary number to limit number of iterations
2067 const int max_iter = 100000;
2069 Cursor & bvcur = d->cursor_;
2070 Cursor const savecur = bvcur;
2072 if (!bvcur.nextInset())
2073 bvcur.forwardInset();
2074 bvcur.beginUndoGroup();
2075 while(bvcur && iterations < max_iter) {
2076 Inset * const ins = bvcur.nextInset();
2079 docstring insname = ins->layoutName();
2080 while (!insname.empty()) {
2081 if (insname == name || name == from_utf8("*")) {
2082 lyx::dispatch(fr, dr);
2083 // we do not want to remember selection here
2084 bvcur.clearSelection();
2088 size_t const i = insname.rfind(':');
2089 if (i == string::npos)
2091 insname = insname.substr(0, i);
2093 // if we did not delete the inset, skip it
2094 if (!bvcur.nextInset() || bvcur.nextInset() == ins)
2095 bvcur.forwardInset();
2098 bvcur.fixIfBroken();
2099 /** This is a dummy undo record only to remember the cursor
2100 * that has just been set; this will be used on a redo action
2101 * (see ticket #10097)
2103 * FIXME: a better fix would be to have a way to set the
2104 * cursor value directly, but I am not sure it is worth it.
2107 bvcur.endUndoGroup();
2108 dr.screenUpdate(Update::Force);
2109 dr.forceBufferUpdate();
2111 if (iterations >= max_iter) {
2113 dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
2115 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
2120 case LFUN_BRANCH_ADD_INSERT: {
2121 docstring branch_name = from_utf8(cmd.getArg(0));
2122 if (branch_name.empty())
2123 if (!Alert::askForText(branch_name, _("Branch name")) ||
2124 branch_name.empty())
2127 DispatchResult drtmp;
2128 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
2129 if (drtmp.error()) {
2130 Alert::warning(_("Branch already exists"), drtmp.message());
2133 docstring const sep = buffer_.params().branchlist().separator();
2134 for (docstring const & branch : getVectorFromString(branch_name, sep))
2135 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch));
2139 case LFUN_KEYMAP_OFF:
2140 getIntl().keyMapOn(false);
2143 case LFUN_KEYMAP_PRIMARY:
2144 getIntl().keyMapPrim();
2147 case LFUN_KEYMAP_SECONDARY:
2148 getIntl().keyMapSec();
2151 case LFUN_KEYMAP_TOGGLE:
2152 getIntl().toggleKeyMap();
2155 case LFUN_DIALOG_SHOW_NEW_INSET: {
2156 string const name = cmd.getArg(0);
2157 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2158 if (decodeInsetParam(name, data, buffer_))
2159 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
2161 lyxerr << "Inset type '" << name <<
2162 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
2166 case LFUN_CITATION_INSERT: {
2167 if (argument.empty()) {
2168 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
2171 // we can have one optional argument, delimited by '|'
2172 // citation-insert <key>|<text_before>
2173 // this should be enhanced to also support text_after
2174 // and citation style
2175 string arg = argument;
2177 if (contains(argument, "|")) {
2178 arg = token(argument, '|', 0);
2179 opt1 = token(argument, '|', 1);
2182 // if our cursor is directly in front of or behind a citation inset,
2183 // we will instead add the new key to it.
2184 Inset * inset = cur.nextInset();
2185 if (!inset || inset->lyxCode() != CITE_CODE)
2186 inset = cur.prevInset();
2187 if (inset && inset->lyxCode() == CITE_CODE) {
2188 InsetCitation * icite = static_cast<InsetCitation *>(inset);
2189 if (icite->addKey(arg)) {
2190 dr.forceBufferUpdate();
2191 dr.screenUpdate(Update::FitCursor | Update::SinglePar);
2193 LYXERR0("Discarding optional argument to citation-insert.");
2198 InsetCommandParams icp(CITE_CODE);
2199 icp["key"] = from_utf8(arg);
2201 icp["before"] = from_utf8(opt1);
2203 from_ascii(InsetCitation::last_literal ? "true" : "false");
2204 string icstr = InsetCommand::params2string(icp);
2205 FuncRequest fr(LFUN_INSET_INSERT, icstr);
2210 case LFUN_INSET_APPLY: {
2211 string const name = cmd.getArg(0);
2212 Inset * inset = editedInset(name);
2214 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
2218 // put cursor in front of inset.
2219 if (!setCursorFromInset(inset)) {
2220 LASSERT(false, break);
2223 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
2224 inset->dispatch(cur, fr);
2225 dr.screenUpdate(cur.result().screenUpdate());
2226 if (cur.result().needBufferUpdate())
2227 dr.forceBufferUpdate();
2232 // The change of language of buffer belongs to the Buffer class.
2233 // We have to do it here because we need a cursor for Undo.
2234 // When Undo::recordUndoBufferParams() is implemented someday
2235 // LFUN_BUFFER_LANGUAGE should be handled by the Buffer class.
2236 case LFUN_BUFFER_LANGUAGE: {
2237 Language const * oldL = buffer_.params().language;
2238 Language const * newL = languages.getLanguage(argument);
2239 if (!newL || oldL == newL)
2241 if (oldL->rightToLeft() == newL->rightToLeft()) {
2242 cur.recordUndoFullBuffer();
2243 buffer_.changeLanguage(oldL, newL);
2244 cur.setCurrentFont();
2245 dr.forceBufferUpdate();
2250 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2251 case LFUN_FILE_INSERT_PLAINTEXT: {
2252 bool const as_paragraph = (act == LFUN_FILE_INSERT_PLAINTEXT_PARA);
2253 string const fname = to_utf8(cmd.argument());
2254 if (!FileName::isAbsolute(fname))
2255 dr.setMessage(_("Absolute filename expected."));
2257 insertPlaintextFile(FileName(fname), as_paragraph);
2262 // With multi-cell table content, we pass down to the inset
2263 if (cur.inTexted() && cur.selection()
2264 && cur.selectionBegin().idx() != cur.selectionEnd().idx()) {
2265 buffer_.dispatch(cmd, dr);
2266 dispatched = dr.dispatched();
2269 cap::copySelection(cur);
2270 cur.message(_("Copy"));
2274 // OK, so try the Buffer itself...
2275 buffer_.dispatch(cmd, dr);
2276 dispatched = dr.dispatched();
2280 buffer_.undo().endUndoGroup();
2281 dr.dispatched(dispatched);
2283 // NOTE: The code below is copied from Cursor::dispatch. If you
2284 // need to modify this, please update the other one too.
2286 // notify insets we just entered/left
2287 if (cursor() != old) {
2288 old.beginUndoGroup();
2290 bool badcursor = notifyCursorLeavesOrEnters(old, cursor());
2292 cursor().fixIfBroken();
2293 resetInlineCompletionPos();
2300 docstring BufferView::requestSelection()
2302 Cursor & cur = d->cursor_;
2304 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
2305 if (!cur.selection()) {
2306 d->xsel_cache_.set = false;
2310 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
2311 if (!d->xsel_cache_.set ||
2312 cur.top() != d->xsel_cache_.cursor ||
2313 cur.realAnchor().top() != d->xsel_cache_.anchor)
2315 d->xsel_cache_.cursor = cur.top();
2316 d->xsel_cache_.anchor = cur.realAnchor().top();
2317 d->xsel_cache_.set = cur.selection();
2318 return cur.selectionAsString(false);
2324 void BufferView::clearSelection()
2326 d->cursor_.clearSelection();
2327 // Clear the selection buffer. Otherwise a subsequent
2328 // middle-mouse-button paste would use the selection buffer,
2329 // not the more current external selection.
2330 cap::clearSelection();
2331 d->xsel_cache_.set = false;
2332 // The buffer did not really change, but this causes the
2333 // redraw we need because we cleared the selection above.
2334 buffer_.changed(false);
2338 void BufferView::resize(int width, int height)
2340 // Update from work area
2344 // Clear the paragraph height cache.
2345 d->par_height_.clear();
2346 // Redo the metrics.
2351 Inset const * BufferView::getCoveringInset(Text const & text,
2354 TextMetrics & tm = d->text_metrics_[&text];
2355 Inset * inset = tm.checkInsetHit(x, y);
2359 if (!inset->descendable(*this))
2360 // No need to go further down if the inset is not
2364 size_t cell_number = inset->nargs();
2365 // Check all the inner cell.
2366 for (size_t i = 0; i != cell_number; ++i) {
2367 Text const * inner_text = inset->getText(i);
2370 Inset const * inset_deeper =
2371 getCoveringInset(*inner_text, x, y);
2373 return inset_deeper;
2381 Inset const * BufferView::clickableMathInset(InsetMathNest const * inset,
2382 CoordCache::Insets const & inset_cache, int x, int y) const
2384 for (size_t i = 0; i < inset->nargs(); ++i) {
2385 MathData const & ar = inset->cell(i);
2386 for (size_t j = 0; j < ar.size(); ++j) {
2387 string const name = lyxerr.debugging(Debug::MATHED)
2388 ? insetName(ar[j].nucleus()->lyxCode())
2390 LYXERR(Debug::MATHED, "Checking inset: " << name);
2391 if (ar[j].nucleus()->clickable(*this, x, y)) {
2392 if (inset_cache.covers(ar[j].nucleus(), x, y)) {
2393 LYXERR(Debug::MATHED, "Clickable inset: "
2395 return ar[j].nucleus();
2398 InsetMathNest const * imn =
2399 ar[j].nucleus()->asNestInset();
2401 Inset const * inner =
2402 clickableMathInset(imn, inset_cache, x, y);
2412 void BufferView::updateHoveredInset() const
2414 // Get inset under mouse, if there is one.
2415 int const x = d->mouse_position_cache_.x_;
2416 int const y = d->mouse_position_cache_.y_;
2417 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
2418 if (covering_inset && covering_inset->asInsetMath()) {
2419 Inset const * inner_inset = clickableMathInset(
2420 covering_inset->asInsetMath()->asNestInset(),
2421 coordCache().getInsets(), x, y);
2423 covering_inset = inner_inset;
2426 d->clickable_inset_ = covering_inset && covering_inset->clickable(*this, x, y);
2428 if (covering_inset == d->last_inset_)
2429 // Same inset, no need to do anything...
2432 bool need_redraw = false;
2433 if (d->last_inset_) {
2434 // Remove the hint on the last hovered inset (if any).
2435 need_redraw |= d->last_inset_->setMouseHover(this, false);
2436 d->last_inset_ = nullptr;
2439 if (covering_inset && covering_inset->setMouseHover(this, true)) {
2441 // Only the insets that accept the hover state, do
2442 // clear the last_inset_, so only set the last_inset_
2443 // member if the hovered setting is accepted.
2444 d->last_inset_ = covering_inset;
2448 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
2449 << d->mouse_position_cache_.x_ << ", "
2450 << d->mouse_position_cache_.y_ << ")");
2452 d->update_strategy_ = DecorationUpdate;
2454 // This event (moving without mouse click) is not passed further.
2455 // This should be changed if it is further utilized.
2456 buffer_.changed(false);
2461 void BufferView::clearLastInset(Inset * inset) const
2463 if (d->last_inset_ != inset) {
2464 LYXERR0("Wrong last_inset!");
2467 d->last_inset_ = nullptr;
2471 bool BufferView::mouseSelecting() const
2473 return d->mouse_selecting_;
2477 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
2479 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
2481 // This is only called for mouse related events including
2482 // LFUN_FILE_OPEN generated by drag-and-drop.
2483 FuncRequest cmd = cmd0;
2485 Cursor old = cursor();
2487 cur.push(buffer_.inset());
2488 cur.selection(d->cursor_.selection());
2490 // Either the inset under the cursor or the
2491 // surrounding Text will handle this event.
2493 // make sure we stay within the screen...
2494 cmd.set_y(min(max(cmd.y(), -1), height_));
2496 d->mouse_position_cache_.x_ = cmd.x();
2497 d->mouse_position_cache_.y_ = cmd.y();
2499 d->mouse_selecting_ =
2500 cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::button1;
2502 if (cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
2503 updateHoveredInset();
2507 // Build temporary cursor.
2508 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x(), cmd.y());
2510 // If inset is not editable, cur.pos() might point behind the
2511 // inset (depending on cmd.x(), cmd.y()). This is needed for
2512 // editing to fix bug 9628, but e.g. the context menu needs a
2513 // cursor in front of the inset.
2514 if ((inset->hasSettings() || !inset->contextMenuName().empty()
2515 || inset->lyxCode() == SEPARATOR_CODE) &&
2516 cur.nextInset() != inset && cur.prevInset() == inset)
2518 } else if (cur.inTexted() && cur.pos()
2519 && cur.paragraph().isEnvSeparator(cur.pos() - 1)) {
2520 // Always place cursor in front of a separator inset.
2524 // Put anchor at the same position.
2527 cur.beginUndoGroup();
2529 // Try to dispatch to an non-editable inset near this position
2530 // via the temp cursor. If the inset wishes to change the real
2531 // cursor it has to do so explicitly by using
2532 // cur.bv().cursor() = cur; (or similar)
2534 inset->dispatch(cur, cmd);
2536 // Now dispatch to the temporary cursor. If the real cursor should
2537 // be modified, the inset's dispatch has to do so explicitly.
2538 if (!inset || !cur.result().dispatched())
2541 // Notify left insets
2543 bool badcursor = old.fixIfBroken() || cur.fixIfBroken();
2544 badcursor = badcursor || notifyCursorLeavesOrEnters(old, cur);
2546 cursor().fixIfBroken();
2551 // Do we have a selection?
2552 theSelection().haveSelection(cursor().selection());
2554 if (cur.needBufferUpdate() || buffer().needUpdate()) {
2555 cur.clearBufferUpdate();
2556 buffer().updateBuffer();
2559 // If the command has been dispatched,
2560 if (cur.result().dispatched() || cur.result().screenUpdate())
2561 processUpdateFlags(cur.result().screenUpdate());
2565 int BufferView::minVisiblePart()
2567 return 2 * defaultRowHeight();
2571 int BufferView::scroll(int pixels)
2574 return scrollDown(pixels);
2576 return scrollUp(-pixels);
2581 int BufferView::scrollDown(int pixels)
2583 Text * text = &buffer_.text();
2584 TextMetrics & tm = d->text_metrics_[text];
2585 int const ymax = height_ + pixels;
2587 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2588 int bottom_pos = last.second->position() + last.second->descent();
2589 if (lyxrc.scroll_below_document)
2590 bottom_pos += height_ - minVisiblePart();
2591 if (last.first + 1 == int(text->paragraphs().size())) {
2592 if (bottom_pos <= height_)
2594 pixels = min(pixels, bottom_pos - height_);
2597 if (bottom_pos > ymax)
2599 tm.newParMetricsDown();
2601 d->anchor_ypos_ -= pixels;
2606 int BufferView::scrollUp(int pixels)
2608 Text * text = &buffer_.text();
2609 TextMetrics & tm = d->text_metrics_[text];
2610 int ymin = - pixels;
2612 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2613 int top_pos = first.second->position() - first.second->ascent();
2614 if (first.first == 0) {
2617 pixels = min(pixels, - top_pos);
2622 tm.newParMetricsUp();
2624 d->anchor_ypos_ += pixels;
2629 bool BufferView::setCursorFromRow(int row)
2631 TexRow::TextEntry start, end;
2632 tie(start,end) = buffer_.texrow().getEntriesFromRow(row);
2633 LYXERR(Debug::OUTFILE,
2634 "setCursorFromRow: for row " << row << ", TexRow has found "
2635 "start (id=" << start.id << ",pos=" << start.pos << "), "
2636 "end (id=" << end.id << ",pos=" << end.pos << ")");
2637 return setCursorFromEntries(start, end);
2641 bool BufferView::setCursorFromEntries(TexRow::TextEntry start,
2642 TexRow::TextEntry end)
2644 DocIterator dit_start, dit_end;
2645 tie(dit_start,dit_end) =
2646 TexRow::getDocIteratorsFromEntries(start, end, buffer_);
2649 // Setting selection start
2650 d->cursor_.clearSelection();
2651 setCursor(dit_start);
2652 // Setting selection end
2654 d->cursor_.resetAnchor();
2655 setCursorSelectionTo(dit_end);
2661 bool BufferView::setCursorFromInset(Inset const * inset)
2663 // are we already there?
2664 if (cursor().nextInset() == inset)
2667 // Inset is not at cursor position. Find it in the document.
2670 while (cur && cur.nextInset() != inset)
2681 void BufferView::gotoLabel(docstring const & label)
2684 bool have_inactive = false;
2685 for (Buffer const * buf : buffer().allRelatives()) {
2687 for (TocItem const & item : *buf->tocBackend().toc("label")) {
2688 if (label == item.str() && item.isOutput()) {
2689 lyx::dispatch(item.action());
2692 // If we find an inactive label, save it for the case
2693 // that no active one is there
2694 if (label == item.str() && !have_inactive) {
2695 have_inactive = true;
2696 action = item.action();
2700 // We only found an inactive label. Go there.
2702 lyx::dispatch(action);
2706 TextMetrics const & BufferView::textMetrics(Text const * t) const
2708 return const_cast<BufferView *>(this)->textMetrics(t);
2712 TextMetrics & BufferView::textMetrics(Text const * t)
2715 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
2716 if (tmc_it == d->text_metrics_.end()) {
2717 tmc_it = d->text_metrics_.emplace(std::piecewise_construct,
2718 std::forward_as_tuple(t),
2719 std::forward_as_tuple(this, const_cast<Text *>(t))).first;
2721 return tmc_it->second;
2725 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2728 return textMetrics(t).parMetrics(pit);
2732 int BufferView::workHeight() const
2738 void BufferView::setCursor(DocIterator const & dit)
2741 size_t const n = dit.depth();
2742 for (size_t i = 0; i < n; ++i)
2743 dit[i].inset().edit(d->cursor_, true);
2745 d->cursor_.setCursor(dit);
2746 d->cursor_.selection(false);
2747 d->cursor_.setCurrentFont();
2749 // It seems on general grounds as if this is probably needed, but
2750 // it is not yet clear.
2751 // See bug #7394 and r38388.
2752 // d->cursor.resetAnchor();
2756 void BufferView::setCursorSelectionTo(DocIterator const & dit)
2758 size_t const n = dit.depth();
2759 for (size_t i = 0; i < n; ++i)
2760 dit[i].inset().edit(d->cursor_, true);
2762 d->cursor_.selection(true);
2763 d->cursor_.setCursorSelectionTo(dit);
2764 d->cursor_.setCurrentFont();
2768 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2770 // Would be wrong to delete anything if we have a selection.
2771 if (cur.selection())
2774 bool need_anchor_change = false;
2775 bool changed = Text::deleteEmptyParagraphMechanism(cur, old,
2776 need_anchor_change);
2778 if (need_anchor_change)
2786 // we would rather not do this here, but it needs to be done before
2787 // the changed() signal is sent.
2788 buffer_.updateBuffer();
2790 buffer_.changed(true);
2795 bool BufferView::mouseSetCursor(Cursor & cur, bool const select)
2797 LASSERT(&cur.bv() == this, return false);
2800 // this event will clear selection so we save selection for
2801 // persistent selection
2802 cap::saveSelection(cursor());
2804 d->cursor_.macroModeClose();
2805 // If a macro has been finalized, the cursor might have been broken
2808 // Has the cursor just left the inset?
2809 bool const leftinset = (&d->cursor_.inset() != &cur.inset());
2811 d->cursor_.fixIfBroken();
2813 // do the dEPM magic if needed
2814 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2815 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2816 // the leftinset bool would not be necessary (badcursor instead).
2817 bool update = leftinset;
2820 d->cursor_.setSelection();
2821 d->cursor_.setCursorSelectionTo(cur);
2823 if (d->cursor_.inTexted())
2824 update |= checkDepm(cur, d->cursor_);
2825 d->cursor_.resetAnchor();
2826 d->cursor_.setCursor(cur);
2827 d->cursor_.clearSelection();
2829 d->cursor_.boundary(cur.boundary());
2830 d->cursor_.finishUndo();
2831 d->cursor_.setCurrentFont();
2833 cur.forceBufferUpdate();
2838 void BufferView::putSelectionAt(DocIterator const & cur,
2839 int length, bool backwards)
2841 d->cursor_.clearSelection();
2847 d->cursor_.pos() += length;
2848 d->cursor_.setSelection(d->cursor_, -length);
2850 d->cursor_.setSelection(d->cursor_, length);
2855 bool BufferView::selectIfEmpty(DocIterator & cur)
2857 if ((cur.inTexted() && !cur.paragraph().empty())
2858 || (cur.inMathed() && !cur.cell().empty()))
2861 pit_type const beg_pit = cur.pit();
2863 // The paragraph associated to this item isn't
2864 // the first one, so it can be selected
2867 // We have to resort to select the space between the
2868 // end of this item and the begin of the next one
2872 // If it is the only item in the document,
2873 // nothing can be selected
2876 pit_type const end_pit = cur.pit();
2877 pos_type const end_pos = cur.pos();
2878 d->cursor_.clearSelection();
2880 d->cursor_.setCursor(cur);
2881 d->cursor_.pit() = beg_pit;
2882 d->cursor_.pos() = 0;
2883 d->cursor_.selection(false);
2884 d->cursor_.resetAnchor();
2885 d->cursor_.pit() = end_pit;
2886 d->cursor_.pos() = end_pos;
2887 d->cursor_.setSelection();
2892 Cursor & BufferView::cursor()
2898 Cursor const & BufferView::cursor() const
2904 bool BufferView::singleParUpdate()
2906 Text & buftext = buffer_.text();
2907 pit_type const bottom_pit = d->cursor_.bottom().pit();
2908 TextMetrics & tm = textMetrics(&buftext);
2909 Dimension const old_dim = tm.parMetrics(bottom_pit).dim();
2911 // make sure inline completion pointer is ok
2912 if (d->inlineCompletionPos_.fixIfBroken())
2913 d->inlineCompletionPos_ = DocIterator();
2915 // In Single Paragraph mode, rebreak only
2916 // the (main text, not inset!) paragraph containing the cursor.
2917 // (if this paragraph contains insets etc., rebreaking will
2918 // recursively descend)
2919 tm.redoParagraph(bottom_pit);
2920 ParagraphMetrics & pm = tm.parMetrics(bottom_pit);
2921 if (pm.height() != old_dim.height()) {
2922 // Paragraph height has changed so we cannot proceed to
2923 // the singlePar optimisation.
2926 // Since position() points to the baseline of the first row, we
2927 // may have to update it. See ticket #11601 for an example where
2928 // the height does not change but the ascent does.
2929 pm.setPosition(pm.position() - old_dim.ascent() + pm.ascent());
2931 tm.updatePosCache(bottom_pit);
2933 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2934 << " y2: " << pm.position() + pm.descent()
2935 << " pit: " << bottom_pit
2936 << " singlepar: 1");
2941 void BufferView::updateMetrics()
2943 updateMetrics(d->update_flags_);
2944 d->update_strategy_ = FullScreenUpdate;
2948 void BufferView::updateMetrics(Update::flags & update_flags)
2950 if (height_ == 0 || width_ == 0)
2953 Text & buftext = buffer_.text();
2954 pit_type const npit = int(buftext.paragraphs().size());
2956 // Clear out the position cache in case of full screen redraw,
2957 d->coord_cache_.clear();
2958 d->math_rows_.clear();
2960 // Clear out paragraph metrics to avoid having invalid metrics
2961 // in the cache from paragraphs not relayouted below
2962 // The complete text metrics will be redone.
2963 d->text_metrics_.clear();
2965 TextMetrics & tm = textMetrics(&buftext);
2967 // make sure inline completion pointer is ok
2968 if (d->inlineCompletionPos_.fixIfBroken())
2969 d->inlineCompletionPos_ = DocIterator();
2971 if (d->anchor_pit_ >= npit)
2972 // The anchor pit must have been deleted...
2973 d->anchor_pit_ = npit - 1;
2975 // Rebreak anchor paragraph.
2976 tm.redoParagraph(d->anchor_pit_);
2977 ParagraphMetrics & anchor_pm = tm.parMetrics(d->anchor_pit_);
2980 if (d->anchor_pit_ == 0) {
2981 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2983 // Complete buffer visible? Then it's easy.
2984 if (scrollRange == 0)
2985 d->anchor_ypos_ = anchor_pm.ascent();
2987 // avoid empty space above the first row
2988 d->anchor_ypos_ = min(d->anchor_ypos_, anchor_pm.ascent());
2991 anchor_pm.setPosition(d->anchor_ypos_);
2992 tm.updatePosCache(d->anchor_pit_);
2994 LYXERR(Debug::PAINTING, "metrics: "
2995 << " anchor pit = " << d->anchor_pit_
2996 << " anchor ypos = " << d->anchor_ypos_);
2998 // Redo paragraphs above anchor if necessary.
2999 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
3000 // We are now just above the anchor paragraph.
3001 pit_type pit1 = d->anchor_pit_ - 1;
3002 for (; pit1 >= 0 && y1 >= 0; --pit1) {
3003 tm.redoParagraph(pit1);
3004 ParagraphMetrics & pm = tm.parMetrics(pit1);
3006 // Save the paragraph position in the cache.
3008 tm.updatePosCache(pit1);
3012 // Redo paragraphs below the anchor if necessary.
3013 int y2 = d->anchor_ypos_ + anchor_pm.descent();
3014 // We are now just below the anchor paragraph.
3015 pit_type pit2 = d->anchor_pit_ + 1;
3016 for (; pit2 < npit && y2 <= height_; ++pit2) {
3017 tm.redoParagraph(pit2);
3018 ParagraphMetrics & pm = tm.parMetrics(pit2);
3020 // Save the paragraph position in the cache.
3022 tm.updatePosCache(pit2);
3026 LYXERR(Debug::PAINTING, "Metrics: "
3027 << " anchor pit = " << d->anchor_pit_
3028 << " anchor ypos = " << d->anchor_ypos_
3031 << " pit1 = " << pit1
3032 << " pit2 = " << pit2);
3034 // metrics is done, full drawing is necessary now
3035 update_flags = (update_flags & ~Update::Force) | Update::ForceDraw;
3037 // Now update the positions of insets in the cache.
3040 if (lyxerr.debugging(Debug::WORKAREA)) {
3041 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
3042 d->coord_cache_.dump();
3047 void BufferView::updatePosCache()
3049 // this is the "nodraw" drawing stage: only set the positions of the
3050 // insets in metrics cache.
3051 frontend::NullPainter np;
3056 void BufferView::insertLyXFile(FileName const & fname, bool const ignorelang)
3058 LASSERT(d->cursor_.inTexted(), return);
3060 // Get absolute path of file and add ".lyx"
3061 // to the filename if necessary
3062 FileName filename = fileSearch(string(), fname.absFileName(), "lyx");
3064 docstring const disp_fn = makeDisplayPath(filename.absFileName());
3065 // emit message signal.
3066 message(bformat(_("Inserting document %1$s..."), disp_fn));
3069 Buffer buf(filename.absFileName(), false);
3070 if (buf.loadLyXFile() == Buffer::ReadSuccess) {
3071 ErrorList & el = buffer_.errorList("Parse");
3072 // Copy the inserted document error list into the current buffer one.
3073 el = buf.errorList("Parse");
3074 ParagraphList & pars = buf.paragraphs();
3076 // set main language of imported file to context language
3077 buf.changeLanguage(buf.language(), d->cursor_.getFont().language());
3078 buffer_.undo().recordUndo(d->cursor_);
3079 cap::pasteParagraphList(d->cursor_, pars,
3080 buf.params().documentClassPtr(),
3081 buf.params().authors(), el);
3082 res = _("Document %1$s inserted.");
3084 res = _("Could not insert document %1$s");
3087 buffer_.changed(true);
3088 // emit message signal.
3089 message(bformat(res, disp_fn));
3093 Point BufferView::coordOffset(DocIterator const & dit) const
3099 // Addup contribution of nested insets, from inside to outside,
3100 // keeping the outer paragraph for a special handling below
3101 for (size_t i = dit.depth() - 1; i >= 1; --i) {
3102 CursorSlice const & sl = dit[i];
3106 // get relative position inside sl.inset()
3107 sl.inset().cursorPos(*this, sl, dit.boundary() && (i + 1 == dit.depth()), xx, yy);
3109 // Make relative position inside of the edited inset relative to sl.inset()
3113 // In case of an RTL inset, the edited inset will be positioned to the left
3116 bool boundary_i = dit.boundary() && i + 1 == dit.depth();
3117 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
3122 // remember width for the case that sl.inset() is positioned in an RTL inset
3123 lastw = sl.inset().dimension(*this).wid;
3125 //lyxerr << "Cursor::getPos, i: "
3126 // << i << " x: " << xx << " y: " << y << endl;
3129 // Add contribution of initial rows of outermost paragraph
3130 CursorSlice const & sl = dit[0];
3131 TextMetrics const & tm = textMetrics(sl.text());
3132 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
3134 LBUFERR(!pm.rows().empty());
3135 y -= pm.rows()[0].ascent();
3137 // FIXME: document this mess
3139 if (sl.pos() > 0 && dit.depth() == 1) {
3141 if (pos && dit.boundary())
3143 // lyxerr << "coordOffset: boundary:" << dit.boundary() << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
3144 rend = pm.pos2row(pos);
3146 rend = pm.pos2row(sl.pos());
3148 size_t rend = pm.pos2row(sl.pos());
3150 for (size_t rit = 0; rit != rend; ++rit)
3151 y += pm.rows()[rit].height();
3152 y += pm.rows()[rend].ascent();
3154 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
3156 // Make relative position from the nested inset now bufferview absolute.
3157 int xx = bottom_tm.cursorX(dit.bottom(), dit.boundary() && dit.depth() == 1);
3160 // In the RTL case place the nested inset at the left of the cursor in
3161 // the outer paragraph
3162 bool boundary_1 = dit.boundary() && 1 == dit.depth();
3163 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
3171 Point BufferView::getPos(DocIterator const & dit) const
3173 if (!paragraphVisible(dit))
3174 return Point(-1, -1);
3176 CursorSlice const & bot = dit.bottom();
3177 TextMetrics const & tm = textMetrics(bot.text());
3179 // offset from outer paragraph
3180 Point p = coordOffset(dit);
3181 p.y_ += tm.parMetrics(bot.pit()).position();
3186 bool BufferView::paragraphVisible(DocIterator const & dit) const
3188 CursorSlice const & bot = dit.bottom();
3189 TextMetrics const & tm = textMetrics(bot.text());
3191 return tm.contains(bot.pit());
3195 void BufferView::caretPosAndDim(Point & p, Dimension & dim) const
3197 Cursor const & cur = cursor();
3198 if (cur.inMathed()) {
3199 MathRow const & mrow = mathRow(&cur.cell());
3200 dim = mrow.caret_dim;
3202 Font const font = cur.real_current_font;
3203 frontend::FontMetrics const & fm = theFontMetrics(font);
3204 // lineWidth() can be 0 to mean 'thin line' on HiDpi, but the
3205 // caret drawing code is not prepared for that.
3206 dim.wid = max(fm.lineWidth(), 1);
3207 dim.asc = fm.maxAscent();
3208 dim.des = fm.maxDescent();
3210 if (lyxrc.cursor_width > 0)
3211 dim.wid = lyxrc.cursor_width;
3214 // center fat carets horizontally
3215 p.x_ -= dim.wid / 2;
3221 void BufferView::buildCaretGeometry(bool complet)
3225 caretPosAndDim(p, dim);
3227 Cursor const & cur = d->cursor_;
3228 Font const & realfont = cur.real_current_font;
3229 frontend::FontMetrics const & fm = theFontMetrics(realfont.fontInfo());
3230 bool const isrtl = realfont.isVisibleRightToLeft();
3231 int const dir = isrtl ? -1 : 1;
3233 frontend::CaretGeometry & cg = d->caret_geometry_;
3236 // The caret itself, slanted for italics in text edit mode except
3237 // for selections because the selection rect does not slant
3238 bool const slant = fm.italic() && cur.inTexted() && !cur.selection();
3239 double const slope = slant ? fm.italicSlope() : 0;
3240 cg.shapes.push_back(
3241 {{iround(p.x_ + dim.asc * slope), p.y_},
3242 {iround(p.x_ - dim.des * slope), p.y_ + dim.height()},
3243 {iround(p.x_ + dir * dim.wid - dim.des * slope), p.y_ + dim.height()},
3244 {iround(p.x_ + dir * dim.wid + dim.asc * slope), p.y_}}
3247 // The language indicator _| (if needed)
3248 Language const * doclang = buffer().params().language;
3249 if (!((realfont.language() == doclang && isrtl == doclang->rightToLeft())
3250 || realfont.language() == latex_language)) {
3251 int const lx = dim.height() / 3;
3252 int const xx = iround(p.x_ - dim.des * slope);
3253 int const yy = p.y_ + dim.height();
3254 cg.shapes.push_back(
3255 {{xx, yy - dim.wid},
3256 {xx + dir * (dim.wid + lx - 1), yy - dim.wid},
3257 {xx + dir * (dim.wid + lx - 1), yy},
3262 // The completion triangle |> (if needed)
3264 int const m = p.y_ + dim.height() / 2;
3265 int const d = dim.height() / 8;
3266 // offset for slanted carret
3267 int const sx = iround((dim.asc - (dim.height() / 2 - d)) * slope);
3268 // starting position x
3269 int const xx = p.x_ + dir * dim.wid + sx;
3270 cg.shapes.push_back(
3274 {xx, m + d - dim.wid},
3275 {xx + dir * d - dim.wid, m},
3276 {xx, m - d + dim.wid}}
3280 // compute extremal x values
3282 cg.right = -1000000;
3284 cg.bottom = -1000000;
3285 for (auto const & shape : cg.shapes)
3286 for (Point const & p : shape) {
3287 cg.left = min(cg.left, p.x_);
3288 cg.right = max(cg.right, p.x_);
3289 cg.top = min(cg.top, p.y_);
3290 cg.bottom = max(cg.bottom, p.y_);
3295 frontend::CaretGeometry const & BufferView::caretGeometry() const
3297 return d->caret_geometry_;
3301 bool BufferView::caretInView() const
3303 if (!paragraphVisible(cursor()))
3307 caretPosAndDim(p, dim);
3309 // does the cursor touch the screen ?
3310 if (p.y_ + dim.height() < 0 || p.y_ >= workHeight())
3316 int BufferView::horizScrollOffset() const
3318 return d->horiz_scroll_offset_;
3322 int BufferView::horizScrollOffset(Text const * text,
3323 pit_type pit, pos_type pos) const
3325 // Is this a row that is currently scrolled?
3326 if (!d->current_row_slice_.empty()
3327 && &text->inset() == d->current_row_slice_.inset().asInsetText()
3328 && pit == d->current_row_slice_.pit()
3329 && pos == d->current_row_slice_.pos())
3330 return d->horiz_scroll_offset_;
3335 void BufferView::setCurrentRowSlice(CursorSlice const & rowSlice)
3337 // nothing to do if the cursor was already on this row
3338 if (d->current_row_slice_ == rowSlice)
3341 // if the (previous) current row was scrolled, we have to
3342 // remember it in order to repaint it next time.
3343 if (d->horiz_scroll_offset_ != 0) {
3344 // search the old row in cache and mark it changed
3345 for (auto & tm_pair : d->text_metrics_) {
3346 if (&tm_pair.first->inset() == rowSlice.inset().asInsetText()) {
3347 tm_pair.second.setRowChanged(rowSlice.pit(), rowSlice.pos());
3348 // We found it, no need to continue.
3354 // Since we changed row, the scroll offset is not valid anymore
3355 d->horiz_scroll_offset_ = 0;
3356 d->current_row_slice_ = rowSlice;
3360 void BufferView::checkCursorScrollOffset()
3362 CursorSlice rowSlice = d->cursor_.bottom();
3363 TextMetrics const & tm = textMetrics(rowSlice.text());
3365 // Stop if metrics have not been computed yet, since it means
3366 // that there is nothing to do.
3367 if (!tm.contains(rowSlice.pit()))
3369 ParagraphMetrics const & pm = tm.parMetrics(rowSlice.pit());
3370 Row const & row = pm.getRow(rowSlice.pos(),
3371 d->cursor_.boundary() && rowSlice == d->cursor_.top());
3372 rowSlice.pos() = row.pos();
3374 // Set the row on which the cursor lives.
3375 setCurrentRowSlice(rowSlice);
3377 // Current x position of the cursor in pixels
3378 int cur_x = getPos(d->cursor_).x_;
3380 // Horizontal scroll offset of the cursor row in pixels
3381 int offset = d->horiz_scroll_offset_;
3382 int const MARGIN = 2 * theFontMetrics(d->cursor_.real_current_font).em()
3384 if (row.right_x() <= workWidth() - row.right_margin) {
3385 // Row is narrower than the work area, no offset needed.
3388 if (cur_x - offset < MARGIN) {
3389 // cursor would be too far right
3390 offset = cur_x - MARGIN;
3391 } else if (cur_x - offset > workWidth() - MARGIN) {
3392 // cursor would be too far left
3393 offset = cur_x - workWidth() + MARGIN;
3395 // Correct the offset to make sure that we do not scroll too much
3398 if (row.right_x() - offset < workWidth() - row.right_margin)
3399 offset = row.right_x() - workWidth() + row.right_margin;
3402 //lyxerr << "cur_x=" << cur_x << ", offset=" << offset << ", row.wid=" << row.width() << ", margin=" << MARGIN << endl;
3404 if (offset != d->horiz_scroll_offset_) {
3405 LYXERR(Debug::PAINTING, "Horiz. scroll offset changed from "
3406 << d->horiz_scroll_offset_ << " to " << offset);
3408 if (d->update_strategy_ == NoScreenUpdate)
3409 d->update_strategy_ = SingleParUpdate;
3412 d->horiz_scroll_offset_ = offset;
3416 void BufferView::draw(frontend::Painter & pain, bool paint_caret)
3418 if (height_ == 0 || width_ == 0)
3420 LYXERR(Debug::PAINTING, (pain.isNull() ? "\t\t--- START NODRAW ---"
3421 : "\t\t*** START DRAWING ***"));
3422 Text & text = buffer_.text();
3423 TextMetrics const & tm = d->text_metrics_[&text];
3424 int const y = tm.first().second->position();
3425 PainterInfo pi(this, pain);
3427 // Check whether the row where the cursor lives needs to be scrolled.
3428 // Update the drawing strategy if needed.
3429 checkCursorScrollOffset();
3431 switch (d->update_strategy_) {
3433 case NoScreenUpdate:
3434 // no screen painting is actually needed. In nodraw stage
3435 // however, the different coordinates of insets and paragraphs
3436 // needs to be updated.
3437 LYXERR(Debug::PAINTING, "Strategy: NoScreenUpdate");
3438 if (pain.isNull()) {
3439 pi.full_repaint = true;
3442 pi.full_repaint = false;
3447 case SingleParUpdate:
3448 pi.full_repaint = false;
3449 LYXERR(Debug::PAINTING, "Strategy: SingleParUpdate");
3450 // In general, only the current row of the outermost paragraph
3451 // will be redrawn. Particular cases where selection spans
3452 // multiple paragraph are correctly detected in TextMetrics.
3456 case DecorationUpdate:
3457 // FIXME: We should also distinguish DecorationUpdate to avoid text
3458 // drawing if possible. This is not possible to do easily right now
3459 // because of the single backing pixmap.
3461 case FullScreenUpdate:
3463 LYXERR(Debug::PAINTING,
3464 ((d->update_strategy_ == FullScreenUpdate)
3465 ? "Strategy: FullScreenUpdate"
3466 : "Strategy: DecorationUpdate"));
3468 // The whole screen, including insets, will be refreshed.
3469 pi.full_repaint = true;
3471 // Clear background.
3472 pain.fillRectangle(0, 0, width_, height_,
3473 pi.backgroundColor(&buffer_.inset()));
3478 // and possibly grey out below
3479 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3480 int const y2 = lastpm.second->position() + lastpm.second->descent();
3483 Color color = buffer().isInternal()
3484 ? Color_background : Color_bottomarea;
3485 pain.fillRectangle(0, y2, width_, height_ - y2, color);
3489 LYXERR(Debug::PAINTING, (pain.isNull() ? "\t\t --- END NODRAW ---"
3490 : "\t\t *** END DRAWING ***"));
3492 // The scrollbar needs an update.
3493 // FIXME: does it always? see ticket #11947.
3494 updateScrollbarParameters();
3496 // Normalize anchor for next time
3497 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
3498 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3499 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
3500 ParagraphMetrics const & pm = tm.parMetrics(pit);
3501 if (pm.position() + pm.descent() > 0) {
3502 if (d->anchor_pit_ != pit
3503 || d->anchor_ypos_ != pm.position())
3504 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
3505 << " anchor ypos = " << d->anchor_ypos_);
3506 d->anchor_pit_ = pit;
3507 d->anchor_ypos_ = pm.position();
3511 if (!pain.isNull()) {
3512 // reset the update flags, everything has been done
3513 d->update_flags_ = Update::None;
3516 // If a caret has to be painted, mark its text row as dirty to
3517 //make sure that it will be repainted on next redraw.
3518 /* FIXME: investigate whether this can be avoided when the cursor did not
3522 Cursor cur(d->cursor_);
3523 while (cur.depth() > 1) {
3524 if (!cur.inTexted())
3526 TextMetrics const & tm = textMetrics(cur.text());
3527 if (d->caret_geometry_.left >= tm.origin().x_
3528 && d->caret_geometry_.right <= tm.origin().x_ + tm.dim().width())
3532 cur.textRow().changed(true);
3537 void BufferView::message(docstring const & msg)
3540 d->gui_->message(msg);
3544 void BufferView::showDialog(string const & name)
3547 d->gui_->showDialog(name, string());
3551 void BufferView::showDialog(string const & name,
3552 string const & data, Inset * inset)
3555 d->gui_->showDialog(name, data, inset);
3559 void BufferView::updateDialog(string const & name, string const & data)
3562 d->gui_->updateDialog(name, data);
3566 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
3572 // FIXME: Move this out of BufferView again
3573 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
3575 if (!fname.isReadableFile()) {
3576 docstring const error = from_ascii(strerror(errno));
3577 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3578 docstring const text =
3579 bformat(_("Could not read the specified document\n"
3580 "%1$s\ndue to the error: %2$s"), file, error);
3581 Alert::error(_("Could not read file"), text);
3585 if (!fname.isReadableFile()) {
3586 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3587 docstring const text =
3588 bformat(_("%1$s\n is not readable."), file);
3589 Alert::error(_("Could not open file"), text);
3593 // FIXME UNICODE: We don't know the encoding of the file
3594 docstring file_content = fname.fileContents("UTF-8");
3595 if (file_content.empty()) {
3596 Alert::error(_("Reading not UTF-8 encoded file"),
3597 _("The file is not UTF-8 encoded.\n"
3598 "It will be read as local 8Bit-encoded.\n"
3599 "If this does not give the correct result\n"
3600 "then please change the encoding of the file\n"
3601 "to UTF-8 with a program other than LyX.\n"));
3602 file_content = fname.fileContents("local8bit");
3605 return normalize_c(file_content);
3609 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
3611 docstring const tmpstr = contentsOfPlaintextFile(f);
3616 Cursor & cur = cursor();
3617 cap::replaceSelection(cur);
3618 buffer_.undo().recordUndo(cur);
3620 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
3622 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
3624 buffer_.changed(true);
3628 docstring const & BufferView::inlineCompletion() const
3630 return d->inlineCompletion_;
3634 size_t BufferView::inlineCompletionUniqueChars() const
3636 return d->inlineCompletionUniqueChars_;
3640 DocIterator const & BufferView::inlineCompletionPos() const
3642 return d->inlineCompletionPos_;
3646 void BufferView::resetInlineCompletionPos()
3648 d->inlineCompletionPos_ = DocIterator();
3652 bool samePar(DocIterator const & a, DocIterator const & b)
3654 if (a.empty() && b.empty())
3656 if (a.empty() || b.empty())
3658 if (a.depth() != b.depth())
3660 return &a.innerParagraph() == &b.innerParagraph();
3664 void BufferView::setInlineCompletion(Cursor const & cur, DocIterator const & pos,
3665 docstring const & completion, size_t uniqueChars)
3667 uniqueChars = min(completion.size(), uniqueChars);
3668 bool changed = d->inlineCompletion_ != completion
3669 || d->inlineCompletionUniqueChars_ != uniqueChars;
3670 bool singlePar = true;
3671 d->inlineCompletion_ = completion;
3672 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
3674 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
3677 DocIterator const & old = d->inlineCompletionPos_;
3679 //lyxerr << "inlineCompletionPos changed" << std::endl;
3680 // old or pos are in another paragraph?
3681 if ((!samePar(cur, pos) && !pos.empty())
3682 || (!samePar(cur, old) && !old.empty())) {
3684 //lyxerr << "different paragraph" << std::endl;
3686 d->inlineCompletionPos_ = pos;
3691 if (singlePar && !(cur.result().screenUpdate() & Update::Force))
3692 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
3694 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::Force);
3699 bool BufferView::clickableInset() const
3701 return d->clickable_inset_;