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"
41 #include "texstream.h"
43 #include "TextMetrics.h"
45 #include "TocBackend.h"
47 #include "insets/InsetBibtex.h"
48 #include "insets/InsetCitation.h"
49 #include "insets/InsetCommand.h" // ChangeRefs
50 #include "insets/InsetGraphics.h"
51 #include "insets/InsetIndex.h"
52 #include "insets/InsetRef.h"
53 #include "insets/InsetText.h"
55 #include "mathed/InsetMathNest.h"
56 #include "mathed/InsetMathRef.h"
57 #include "mathed/MathData.h"
58 #include "mathed/MathRow.h"
60 #include "frontends/alert.h"
61 #include "frontends/CaretGeometry.h"
62 #include "frontends/Delegates.h"
63 #include "frontends/FontMetrics.h"
64 #include "frontends/NullPainter.h"
65 #include "frontends/Painter.h"
66 #include "frontends/Selection.h"
67 #include "frontends/Clipboard.h"
69 #include "support/convert.h"
70 #include "support/debug.h"
71 #include "support/docstring.h"
72 #include "support/filetools.h"
73 #include "support/gettext.h"
74 #include "support/lassert.h"
75 #include "support/Length.h"
76 #include "support/lstrings.h"
77 #include "support/lyxlib.h"
78 #include "support/types.h"
90 using namespace lyx::support;
94 namespace Alert = frontend::Alert;
98 /// Return an inset of this class if it exists at the current cursor position
100 T * getInsetByCode(Cursor const & cur, InsetCode code)
102 DocIterator it = cur;
103 Inset * inset = it.nextInset();
104 if (inset && inset->lyxCode() == code)
105 return static_cast<T*>(inset);
110 /// Note that comparing contents can only be used for InsetCommand
111 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
112 docstring const & contents)
114 DocIterator tmpdit = dit;
117 Inset const * inset = tmpdit.nextInset();
119 bool const valid_code = std::find(codes.begin(), codes.end(),
120 inset->lyxCode()) != codes.end();
121 InsetCommand const * ic = inset->asInsetCommand();
122 bool const same_or_no_contents = contents.empty()
123 || (ic && (ic->getFirstNonOptParam() == contents));
125 if (valid_code && same_or_no_contents) {
130 tmpdit.forwardInset();
137 /// Looks for next inset with one of the given codes.
138 /// Note that same_content can only be used for InsetCommand
139 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
143 DocIterator tmpdit = dit;
144 tmpdit.forwardInset();
148 Inset const * inset = tmpdit.nextInset();
149 if (same_content && inset) {
150 InsetCommand const * ic = inset->asInsetCommand();
152 bool const valid_code = std::find(codes.begin(), codes.end(),
153 ic->lyxCode()) != codes.end();
155 contents = ic->getFirstNonOptParam();
159 if (!findNextInset(tmpdit, codes, contents)) {
160 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
161 inset = &tmpdit.bottom().inset();
162 tmpdit = doc_iterator_begin(&inset->buffer(), inset);
163 if (!findNextInset(tmpdit, codes, contents))
175 /// Moves cursor to the next inset with one of the given codes.
176 bool gotoInset(BufferView * bv, vector<InsetCode> const & codes,
179 Cursor tmpcur = bv->cursor();
180 if (!findInset(tmpcur, codes, same_content)) {
181 bv->cursor().message(_("No more insets"));
185 tmpcur.clearSelection();
186 bv->setCursor(tmpcur);
187 return bv->scrollToCursor(bv->cursor(), false, true);
191 /// A map from a Text to the associated text metrics
192 typedef map<Text const *, TextMetrics> TextMetricsCache;
194 enum ScreenUpdateStrategy {
204 /////////////////////////////////////////////////////////////////////
208 /////////////////////////////////////////////////////////////////////
210 struct BufferView::Private
212 Private(BufferView & bv) :
213 update_strategy_(FullScreenUpdate),
214 update_flags_(Update::Force),
215 cursor_(bv), anchor_pit_(0), anchor_ypos_(0),
216 wh_(0), inlineCompletionUniqueChars_(0),
217 last_inset_(nullptr), mouse_position_cache_(),
218 gui_(nullptr), bookmark_edit_position_(-1),
219 horiz_scroll_offset_(0), clickable_inset_(false)
221 xsel_cache_.set = false;
225 ScrollbarParameters scrollbarParameters_;
227 ScreenUpdateStrategy update_strategy_;
229 Update::flags update_flags_;
231 CoordCache coord_cache_;
233 typedef unordered_map<MathData const *, MathRow> MathRows;
236 /// this is used to handle XSelection events in the right manner.
245 pit_type anchor_pit_;
248 /// Estimated average par height for scrollbar.
251 vector<int> par_height_;
254 DocIterator inlineCompletionPos_;
256 docstring inlineCompletion_;
258 size_t inlineCompletionUniqueChars_;
260 /// keyboard mapping object.
263 /// last visited inset.
264 /** kept to send setMouseHover(false).
265 * Not owned, so don't delete.
267 Inset const * last_inset_;
269 /// position of the mouse at the time of the last mouse move
270 /// This is used to update the hovering status of inset in
271 /// cases where the buffer is scrolled, but the mouse didn't move.
272 Point mouse_position_cache_;
274 mutable TextMetricsCache text_metrics_;
277 /** Not owned, so don't delete.
279 frontend::GuiBufferViewDelegate * gui_;
282 map<string, Inset *> edited_insets_;
284 /// When the row where the cursor lies is scrolled, this
285 /// contains the scroll offset
286 // cache for id of the paragraph which was edited the last time
287 int bookmark_edit_position_;
289 int horiz_scroll_offset_;
290 /// a slice pointing to the start of the row where the cursor
291 /// is (at last draw time)
292 CursorSlice current_row_slice_;
293 /// are we hovering something that we can click
294 bool clickable_inset_;
295 /// shape of the caret
296 frontend::CaretGeometry caret_geometry_;
298 bool mouse_selecting_ = false;
302 BufferView::BufferView(Buffer & buf)
303 : width_(0), height_(0), full_screen_(false), buffer_(buf),
304 d(new Private(*this))
306 d->xsel_cache_.set = false;
307 d->intl_.initKeyMapper(lyxrc.use_kbmap);
309 d->cursor_.setBuffer(&buf);
310 d->cursor_.push(buffer_.inset());
311 d->cursor_.resetAnchor();
312 d->cursor_.setCurrentFont();
314 buffer_.updatePreviews();
318 BufferView::~BufferView()
320 // current buffer is going to be switched-off, save cursor pos
321 // Ideally, the whole cursor stack should be saved, but session
322 // currently can only handle bottom (whole document) level pit and pos.
323 // That is to say, if a cursor is in a nested inset, it will be
324 // restore to the left of the top level inset.
325 LastFilePosSection::FilePos fp;
326 fp.file = buffer_.fileName();
327 fp.pit = d->cursor_.bottom().pit();
328 fp.pos = d->cursor_.bottom().pos();
329 theSession().lastFilePos().save(fp);
332 d->last_inset_->setMouseHover(this, false);
338 int BufferView::defaultMargin() const
340 // The value used to be hardcoded to 10
341 return zoomedPixels(20);
345 int BufferView::rightMargin() const
347 const int screen_width = inPixels(lyxrc.screen_width);
349 // The additional test for the case the outliner is opened.
350 if (!lyxrc.screen_limit || width_ < screen_width + 2 * defaultMargin()) {
351 return defaultMargin();
353 return (width_ - screen_width) / 2;
358 int BufferView::leftMargin() const
360 return rightMargin();
364 int BufferView::topMargin() const
366 // Original value was 20px at 100dpi. For internal buffers like in
367 // advanced search and replace, a value of 5px is enough.
368 return zoomedPixels(buffer().isInternal() ? 5 : 20);
372 int BufferView::bottomMargin() const
378 int BufferView::inPixels(Length const & len) const
380 Font const font = buffer().params().getFont();
381 return len.inPixels(workWidth(), theFontMetrics(font).em());
385 int BufferView::zoomedPixels(int pix) const
387 // FIXME: the dpi setting should really depend on the BufferView
388 // (think different monitors).
390 // Zoom factor specified by user in percent
391 double const zoom = lyxrc.currentZoom / 100.0; // [percent]
393 // DPI setting for monitor relative to 100dpi
394 double const dpizoom = lyxrc.dpi / 100.0; // [per 100dpi]
396 return support::iround(pix * zoom * dpizoom);
400 bool BufferView::isTopScreen() const
402 return 0 == d->scrollbarParameters_.min;
406 bool BufferView::isBottomScreen() const
408 return 0 == d->scrollbarParameters_.max;
412 Intl & BufferView::getIntl()
418 Intl const & BufferView::getIntl() const
424 CoordCache & BufferView::coordCache()
426 return d->coord_cache_;
430 CoordCache const & BufferView::coordCache() const
432 return d->coord_cache_;
436 MathRow const & BufferView::mathRow(MathData const * cell) const
438 auto it = d->math_rows_.find(cell);
439 LATTEST(it != d->math_rows_.end());
444 void BufferView::setMathRow(MathData const * cell, MathRow const & mrow)
446 d->math_rows_[cell] = mrow;
450 Buffer & BufferView::buffer()
456 Buffer const & BufferView::buffer() const
462 docstring const & BufferView::searchRequestCache() const
464 return theClipboard().getFindBuffer();
468 void BufferView::setSearchRequestCache(docstring const & text)
476 docstring const search = string2find(text, casesensitive, matchword,
477 forward, wrap, instant, onlysel);
478 theClipboard().setFindBuffer(search);
482 bool BufferView::needsFitCursor() const
484 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
485 frontend::FontMetrics const & fm =
486 theFontMetrics(d->cursor_.getFont().fontInfo());
487 int const asc = fm.maxAscent();
488 int const des = fm.maxDescent();
489 Point const p = getPos(d->cursor_);
490 if (p.y_ - asc >= 0 && p.y_ + des < height_)
499 // this is for debugging only.
500 string flagsAsString(Update::flags flags)
502 if (flags == Update::None)
504 return string((flags & Update::FitCursor) ? "FitCursor " : "")
505 + ((flags & Update::Force) ? "Force " : "")
506 + ((flags & Update::ForceDraw) ? "ForceDraw " : "")
507 + ((flags & Update::SinglePar) ? "SinglePar " : "")
508 + ((flags & Update::Decoration) ? "Decoration " : "");
513 void BufferView::processUpdateFlags(Update::flags flags)
515 LYXERR(Debug::PAINTING, "BufferView::processUpdateFlags( "
516 << flagsAsString(flags) << ") buffer: " << &buffer_);
518 // Case when no explicit update is requested.
519 if (flags == Update::None)
522 /* FIXME We would like to avoid doing this here, since it is very
523 * expensive and is called in updateBuffer already. However, even
524 * inserting a plain character can invalidate the overly fragile
525 * tables of child documents built by updateMacros. Some work is
526 * needed to avoid doing that when not necessary.
528 buffer_.updateMacros();
530 // First check whether the metrics and inset positions should be updated
531 if (flags & Update::Force) {
532 // This will update the CoordCache items and replace Force
533 // with ForceDraw in flags.
534 updateMetrics(flags);
537 // Detect whether we can only repaint a single paragraph (if we
538 // are not already redrawing all).
539 // We handle this before FitCursor because the later will require
540 // correct metrics at cursor position.
541 if (!(flags & Update::ForceDraw)
542 && (flags & Update::SinglePar)
543 && !singleParUpdate())
544 updateMetrics(flags);
546 // Then make sure that the screen contains the cursor if needed
547 if (flags & Update::FitCursor) {
548 if (needsFitCursor()) {
549 // First try to make the selection start visible
550 // (which is just the cursor when there is no selection)
551 scrollToCursor(d->cursor_.selectionBegin(), false, false);
552 // Metrics have to be recomputed (maybe again)
554 // Is the cursor visible? (only useful if cursor is at end of selection)
555 if (needsFitCursor()) {
556 // then try to make cursor visible instead
557 scrollToCursor(d->cursor_, false, false);
558 // Metrics have to be recomputed (maybe again)
559 updateMetrics(flags);
562 flags = flags & ~Update::FitCursor;
565 // Add flags to the the update flags. These will be reset to None
566 // after the redraw is actually done
567 d->update_flags_ = d->update_flags_ | flags;
568 LYXERR(Debug::PAINTING, "Cumulative flags: " << flagsAsString(flags));
570 // Now compute the update strategy
571 // Possibly values in flag are None, SinglePar, Decoration, ForceDraw
572 LATTEST((d->update_flags_ & ~(Update::None | Update::SinglePar
573 | Update::Decoration | Update::ForceDraw)) == 0);
575 if (d->update_flags_ & Update::ForceDraw)
576 d->update_strategy_ = FullScreenUpdate;
577 else if (d->update_flags_ & Update::Decoration)
578 d->update_strategy_ = DecorationUpdate;
579 else if (d->update_flags_ & Update::SinglePar)
580 d->update_strategy_ = SingleParUpdate;
582 // no need to redraw anything.
583 d->update_strategy_ = NoScreenUpdate;
586 updateHoveredInset();
589 buffer_.changed(false);
593 void BufferView::updateScrollbarParameters()
595 if (height_ == 0 && width_ == 0)
598 // We prefer fixed size line scrolling.
599 d->scrollbarParameters_.single_step = defaultRowHeight();
600 // We prefer full screen page scrolling.
601 d->scrollbarParameters_.page_step = height_;
603 Text & t = buffer_.text();
604 TextMetrics & tm = d->text_metrics_[&t];
606 LYXERR(Debug::GUI, " Updating scrollbar: height: "
607 << t.paragraphs().size()
608 << " curr par: " << d->cursor_.bottom().pit()
609 << " default height " << defaultRowHeight());
611 size_t const parsize = t.paragraphs().size();
612 if (d->par_height_.size() != parsize) {
613 d->par_height_.clear();
614 // FIXME: We assume a default paragraph height of 2 rows. This
615 // should probably be pondered with the screen width.
616 d->par_height_.resize(parsize, defaultRowHeight() * 2);
619 // Look at paragraph heights on-screen
620 pair<pit_type, ParagraphMetrics const *> first = tm.first();
621 pair<pit_type, ParagraphMetrics const *> last = tm.last();
622 for (pit_type pit = first.first; pit <= last.first; ++pit) {
623 d->par_height_[pit] = tm.parMetrics(pit).height();
624 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
625 << d->par_height_[pit]);
628 int top_pos = first.second->position() - first.second->ascent();
629 int bottom_pos = last.second->position() + last.second->descent();
630 bool first_visible = first.first == 0 && top_pos >= 0;
631 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
632 if (first_visible && last_visible) {
633 d->scrollbarParameters_.min = 0;
634 d->scrollbarParameters_.max = 0;
638 d->scrollbarParameters_.min = top_pos;
639 for (size_t i = 0; i != size_t(first.first); ++i)
640 d->scrollbarParameters_.min -= d->par_height_[i];
641 d->scrollbarParameters_.max = bottom_pos;
642 for (size_t i = last.first + 1; i != parsize; ++i)
643 d->scrollbarParameters_.max += d->par_height_[i];
645 // The reference is the top position so we remove one page.
646 if (lyxrc.scroll_below_document)
647 d->scrollbarParameters_.max -= minVisiblePart();
649 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
651 // 0 must be inside the range as it denotes the current position
652 if (d->scrollbarParameters_.max < 0)
653 d->scrollbarParameters_.max = 0;
654 if (d->scrollbarParameters_.min > 0)
655 d->scrollbarParameters_.min = 0;
659 ScrollbarParameters const & BufferView::scrollbarParameters() const
661 return d->scrollbarParameters_;
665 docstring BufferView::toolTip(int x, int y) const
667 // Get inset under mouse, if there is one.
668 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
670 // No inset, no tooltip...
672 return covering_inset->toolTip(*this, x, y);
676 string BufferView::contextMenu(int x, int y) const
678 //If there is a selection, return the containing inset menu
679 if (d->cursor_.selection())
680 return d->cursor_.inset().contextMenu(*this, x, y);
682 // Get inset under mouse, if there is one.
683 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
684 if (covering_inset) {
685 if (covering_inset->asInsetMath()) {
686 CoordCache::Insets const & inset_cache =
687 coordCache().getInsets();
688 Inset const * inner_inset = mathContextMenu(
689 covering_inset->asInsetMath()->asNestInset(),
692 return inner_inset->contextMenu(*this, x, y);
694 return covering_inset->contextMenu(*this, x, y);
697 return buffer_.inset().contextMenu(*this, x, y);
701 Inset const * BufferView::mathContextMenu(InsetMathNest const * inset,
702 CoordCache::Insets const & inset_cache, int x, int y) const
704 for (size_t i = 0; i < inset->nargs(); ++i) {
705 MathData const & ar = inset->cell(i);
706 for (size_t j = 0; j < ar.size(); ++j) {
707 string const name = lyxerr.debugging(Debug::MATHED)
708 ? insetName(ar[j].nucleus()->lyxCode())
710 LYXERR(Debug::MATHED, "Examining inset: " << name);
711 if (!ar[j].nucleus()->contextMenuName().empty()) {
712 if (inset_cache.covers(ar[j].nucleus(), x, y)) {
713 LYXERR(Debug::MATHED, "Hit inset: "
715 return ar[j].nucleus();
718 InsetMathNest const * imn =
719 ar[j].nucleus()->asNestInset();
721 Inset const * inner =
722 mathContextMenu(imn, inset_cache, x, y);
732 void BufferView::scrollDocView(int const pixels, bool update)
734 // The scrollbar values are relative to the top of the screen, therefore the
735 // offset is equal to the target value.
737 // No scrolling at all? No need to redraw anything
741 // If the offset is less than 2 screen height, prefer to scroll instead.
742 if (abs(pixels) <= 2 * height_) {
743 d->anchor_ypos_ -= pixels;
744 processUpdateFlags(Update::Force);
748 // cut off at the top
749 if (pixels <= d->scrollbarParameters_.min) {
750 DocIterator dit = doc_iterator_begin(&buffer_);
751 showCursor(dit, false, false, update);
752 LYXERR(Debug::SCROLLING, "scroll to top");
756 // cut off at the bottom
757 if (pixels >= d->scrollbarParameters_.max) {
758 DocIterator dit = doc_iterator_end(&buffer_);
760 showCursor(dit, false, false, update);
761 LYXERR(Debug::SCROLLING, "scroll to bottom");
765 // find paragraph at target position
766 int par_pos = d->scrollbarParameters_.min;
768 for (; i != int(d->par_height_.size()); ++i) {
769 par_pos += d->par_height_[i];
770 if (par_pos >= pixels)
774 if (par_pos < pixels) {
775 // It seems we didn't find the correct pit so stay on the safe side and
777 LYXERR0("scrolling position not found!");
778 scrollDocView(d->scrollbarParameters_.max, update);
782 DocIterator dit = doc_iterator_begin(&buffer_);
784 LYXERR(Debug::SCROLLING, "pixels = " << pixels << " -> scroll to pit " << i);
785 showCursor(dit, false, false, update);
789 // FIXME: this method is not working well.
790 void BufferView::setCursorFromScrollbar()
792 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
794 int const height = 2 * defaultRowHeight();
795 int const first = height;
796 int const last = height_ - height;
798 Cursor const & oldcur = d->cursor_;
800 switch (cursorStatus(oldcur)) {
808 int const y = getPos(oldcur).y_;
809 newy = min(last, max(y, first));
813 // We reset the cursor because cursorStatus() does not
814 // work when the cursor is within mathed.
817 tm.setCursorFromCoordinates(cur, 0, newy);
819 // update the bufferview cursor and notify insets
820 // FIXME: Care about the d->cursor_ flags to redraw if needed
821 Cursor old = d->cursor_;
823 // the DEPM call in mouseSetCursor() might have destroyed the
824 // paragraph the cursor is in.
825 bool badcursor = old.fixIfBroken();
826 badcursor |= notifyCursorLeavesOrEnters(old, d->cursor_);
828 d->cursor_.fixIfBroken();
832 Change const BufferView::getCurrentChange() const
834 if (!d->cursor_.selection())
835 return Change(Change::UNCHANGED);
837 DocIterator dit = d->cursor_.selectionBegin();
838 // The selected content might have been changed (see #7685)
839 dit = dit.getInnerText();
840 return dit.paragraph().lookupChange(dit.pos());
844 // this could be used elsewhere as well?
845 // FIXME: This does not work within mathed!
846 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
848 Point const p = getPos(dit);
851 if (p.y_ > workHeight())
857 void BufferView::bookmarkEditPosition()
859 // Don't eat cpu time for each keystroke
860 if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
863 d->bookmark_edit_position_ = d->cursor_.paragraph().id();
867 void BufferView::saveBookmark(unsigned int idx)
869 if (buffer().isInternal())
872 // tentatively save bookmark, id and pos will be used to
873 // acturately locate a bookmark in a 'live' lyx session.
874 // pit and pos will be updated with bottom level pit/pos
876 theSession().bookmarks().save(
878 d->cursor_.bottom().pit(),
879 d->cursor_.bottom().pos(),
880 d->cursor_.paragraph().id(),
885 // emit message signal.
886 message(_("Save bookmark"));
890 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
891 int top_id, pos_type top_pos)
893 bool success = false;
896 d->cursor_.clearSelection();
898 // if a valid par_id is given, try it first
899 // This is the case for a 'live' bookmark when unique paragraph ID
900 // is used to track bookmarks.
902 dit = buffer_.getParFromID(top_id);
904 dit.pos() = min(dit.paragraph().size(), top_pos);
905 // Some slices of the iterator may not be
906 // reachable (e.g. closed collapsible inset)
907 // so the dociterator may need to be
908 // shortened. Otherwise, setCursor may crash
909 // lyx when the cursor can not be set to these
911 size_t const n = dit.depth();
912 for (size_t i = 0; i < n; ++i)
913 if (!dit[i].inset().editable()) {
921 // if top_id == 0, or searching through top_id failed
922 // This is the case for a 'restored' bookmark when only bottom
923 // (document level) pit was saved. Because of this, bookmark
924 // restoration is inaccurate. If a bookmark was within an inset,
925 // it will be restored to the left of the outmost inset that contains
927 if (!success && bottom_pit < int(buffer_.paragraphs().size())) {
928 dit = doc_iterator_begin(&buffer_);
930 dit.pit() = bottom_pit;
931 dit.pos() = min(bottom_pos, dit.paragraph().size());
936 // Note: only bottom (document) level pit is set.
938 // set the current font.
939 d->cursor_.setCurrentFont();
940 // Do not forget to reset the anchor (see #9912)
941 d->cursor_.resetAnchor();
942 processUpdateFlags(Update::Force | Update::FitCursor);
949 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
951 if (d->cursor_.real_current_font.isRightToLeft()) {
952 if (d->intl_.keymap == Intl::PRIMARY)
953 d->intl_.keyMapSec();
955 if (d->intl_.keymap == Intl::SECONDARY)
956 d->intl_.keyMapPrim();
959 d->intl_.getTransManager().translateAndInsert(c, t, cur);
963 int BufferView::workWidth() const
969 void BufferView::recenter()
971 showCursor(d->cursor_, true, false, true);
975 void BufferView::showCursor()
977 showCursor(d->cursor_, false, false, true);
981 void BufferView::showCursor(DocIterator const & dit,
982 bool recenter, bool force, bool update)
984 if (scrollToCursor(dit, recenter, force) && update)
985 processUpdateFlags(Update::Force);
989 bool BufferView::scrollToCursor(DocIterator const & dit, bool const recenter, bool force)
991 // We are not properly started yet, delay until resizing is done.
996 LYXERR(Debug::SCROLLING, "recentering and scrolling to cursor");
998 LYXERR(Debug::SCROLLING, "scrolling to cursor");
1000 CursorSlice const & bot = dit.bottom();
1001 TextMetrics & tm = textMetrics(bot.text());
1003 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
1004 pos_type bot_pit = bot.pit();
1005 if (bot_pit > max_pit) {
1006 // FIXME: Why does this happen?
1007 LYXERR0("bottom pit is greater that max pit: "
1008 << bot_pit << " > " << max_pit);
1012 if (bot_pit == tm.first().first - 1)
1013 tm.newParMetricsUp();
1014 else if (bot_pit == tm.last().first + 1)
1015 tm.newParMetricsDown();
1017 if (tm.contains(bot_pit) && !force) {
1018 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
1019 LBUFERR(!pm.rows().empty());
1020 // FIXME: smooth scrolling doesn't work in mathed.
1021 CursorSlice const & cs = dit.innerTextSlice();
1022 int const ypos = pm.position() + coordOffset(dit).y_;
1023 ParagraphMetrics const & inner_pm =
1024 textMetrics(cs.text()).parMetrics(cs.pit());
1025 Dimension const & row_dim =
1026 inner_pm.getRow(cs.pos(), dit.boundary()).dim();
1029 scrolled = scroll(ypos - height_/2);
1031 // We try to visualize the whole row, if the row height is larger than
1032 // the screen height, we scroll to a heuristic value of height_ / 4.
1033 // FIXME: This heuristic value should be replaced by a recursive search
1034 // for a row in the inset that can be visualized completely.
1035 else if (row_dim.height() > height_) {
1036 if (ypos < defaultRowHeight())
1037 scrolled = scroll(ypos - height_ / 4);
1038 else if (ypos > height_ - defaultRowHeight())
1039 scrolled = scroll(ypos - 3 * height_ / 4);
1042 // If the top part of the row falls of the screen, we scroll
1043 // up to align the top of the row with the top of the screen.
1044 else if (ypos - row_dim.ascent() < 0 && ypos < height_) {
1045 int const ynew = row_dim.ascent();
1046 scrolled = scrollUp(ynew - ypos);
1049 // If the bottom of the row falls of the screen, we scroll down.
1050 else if (ypos + row_dim.descent() > height_ && ypos > 0) {
1051 int const ynew = height_ - row_dim.descent();
1052 scrolled = scrollDown(ypos - ynew);
1055 // else, nothing to do, the cursor is already visible so we just return.
1056 return scrolled != 0;
1059 // fix inline completion position
1060 if (d->inlineCompletionPos_.fixIfBroken())
1061 d->inlineCompletionPos_ = DocIterator();
1063 tm.redoParagraph(bot_pit);
1064 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
1065 int const offset = coordOffset(dit).y_;
1067 d->anchor_pit_ = bot_pit;
1068 CursorSlice const & cs = dit.innerTextSlice();
1069 ParagraphMetrics const & inner_pm =
1070 textMetrics(cs.text()).parMetrics(cs.pit());
1071 Dimension const & row_dim =
1072 inner_pm.getRow(cs.pos(), dit.boundary()).dim();
1075 d->anchor_ypos_ = height_/2;
1076 else if (d->anchor_pit_ == 0)
1077 d->anchor_ypos_ = offset + pm.ascent();
1078 else if (d->anchor_pit_ == max_pit)
1079 d->anchor_ypos_ = height_ - offset - row_dim.descent();
1080 else if (offset > height_)
1081 d->anchor_ypos_ = height_ - offset - row_dim.descent();
1083 d->anchor_ypos_ = row_dim.ascent();
1089 void BufferView::makeDocumentClass()
1091 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
1092 buffer_.params().makeDocumentClass(buffer_.isClone(), buffer_.isInternal());
1093 updateDocumentClass(olddc);
1097 void BufferView::updateDocumentClass(DocumentClassConstPtr olddc)
1099 StableDocIterator backcur(d->cursor_);
1100 ErrorList & el = buffer_.errorList("Class Switch");
1101 cap::switchBetweenClasses(
1102 olddc, buffer_.params().documentClassPtr(),
1103 static_cast<InsetText &>(buffer_.inset()), el);
1105 setCursor(backcur.asDocIterator(&buffer_));
1107 buffer_.errors("Class Switch");
1111 /** Return the change status at cursor position, taking into account the
1112 * status at each level of the document iterator (a table in a deleted
1113 * footnote is deleted).
1114 * When \param outer is true, the top slice is not looked at.
1116 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
1118 size_t const depth = dit.depth() - (outer ? 1 : 0);
1120 for (size_t i = 0 ; i < depth ; ++i) {
1121 CursorSlice const & slice = dit[i];
1122 if (!slice.inset().inMathed()
1123 && slice.pos() < slice.paragraph().size()) {
1124 Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
1125 if (ch != Change::UNCHANGED)
1129 return Change::UNCHANGED;
1133 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1135 FuncCode const act = cmd.action();
1137 // Can we use a readonly buffer?
1138 if (buffer_.isReadonly()
1139 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1140 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1141 if (buffer_.hasReadonlyFlag())
1142 flag.message(from_utf8(N_("Document is read-only")));
1144 flag.message(from_utf8(N_("Document has been modified externally")));
1145 flag.setEnabled(false);
1149 // Are we in a DELETED change-tracking region?
1150 if (lookupChangeType(d->cursor_, true) == Change::DELETED
1151 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1152 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1153 flag.message(from_utf8(N_("This portion of the document is deleted.")));
1154 flag.setEnabled(false);
1158 Cursor & cur = d->cursor_;
1160 if (cur.getStatus(cmd, flag))
1165 // FIXME: This is a bit problematic because we don't check if this is
1166 // a document BufferView or not for these LFUNs. We probably have to
1167 // dispatch both to currentBufferView() and, if that fails,
1168 // to documentBufferView(); same as we do now for current Buffer and
1169 // document Buffer. Ideally those LFUN should go to Buffer as they
1170 // operate on the full Buffer and the cursor is only needed either for
1171 // an Undo record or to restore a cursor position. But we don't know
1172 // how to do that inside Buffer of course.
1173 case LFUN_BUFFER_PARAMS_APPLY:
1174 case LFUN_LAYOUT_MODULES_CLEAR:
1175 case LFUN_LAYOUT_MODULE_ADD:
1176 case LFUN_LAYOUT_RELOAD:
1177 case LFUN_TEXTCLASS_APPLY:
1178 case LFUN_TEXTCLASS_LOAD:
1179 flag.setEnabled(!buffer_.isReadonly());
1183 // We do not use the LyXAction flag for readonly because Undo sets the
1184 // buffer clean/dirty status by itself.
1185 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasUndoStack());
1188 // We do not use the LyXAction flag for readonly because Redo sets the
1189 // buffer clean/dirty status by itself.
1190 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasRedoStack());
1192 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1193 case LFUN_FILE_INSERT_PLAINTEXT: {
1194 docstring const & fname = cmd.argument();
1195 if (!FileName::isAbsolute(to_utf8(fname))) {
1196 flag.message(_("Absolute filename expected."));
1199 flag.setEnabled(cur.inTexted());
1202 case LFUN_FILE_INSERT:
1203 case LFUN_BOOKMARK_SAVE:
1204 // FIXME: Actually, these LFUNS should be moved to Text
1205 flag.setEnabled(cur.inTexted());
1208 case LFUN_FONT_STATE:
1209 case LFUN_LABEL_INSERT:
1210 case LFUN_INFO_INSERT:
1211 case LFUN_PARAGRAPH_GOTO:
1212 case LFUN_NOTE_NEXT:
1213 case LFUN_REFERENCE_NEXT:
1214 case LFUN_WORD_FIND:
1215 case LFUN_WORD_FIND_FORWARD:
1216 case LFUN_WORD_FIND_BACKWARD:
1217 case LFUN_WORD_REPLACE:
1220 case LFUN_MARK_TOGGLE:
1221 case LFUN_SEARCH_STRING_SET:
1222 case LFUN_SCREEN_RECENTER:
1223 case LFUN_SCREEN_SHOW_CURSOR:
1224 case LFUN_BIBTEX_DATABASE_ADD:
1225 case LFUN_BIBTEX_DATABASE_DEL:
1226 case LFUN_STATISTICS:
1227 case LFUN_KEYMAP_OFF:
1228 case LFUN_KEYMAP_PRIMARY:
1229 case LFUN_KEYMAP_SECONDARY:
1230 case LFUN_KEYMAP_TOGGLE:
1231 case LFUN_INSET_SELECT_ALL:
1232 flag.setEnabled(true);
1235 case LFUN_GRAPHICS_UNIFY:
1236 flag.setEnabled(cur.countInsetsInSelection(GRAPHICS_CODE)>1);
1239 case LFUN_WORD_FINDADV: {
1240 FindAndReplaceOptions opt;
1241 istringstream iss(to_utf8(cmd.argument()));
1243 flag.setEnabled(opt.repl_buf_name.empty()
1244 || !buffer_.isReadonly());
1248 case LFUN_LABEL_GOTO:
1249 flag.setEnabled(!cmd.argument().empty()
1250 || getInsetByCode<InsetRef>(cur, REF_CODE)
1251 || getInsetByCode<InsetMathRef>(cur, MATH_REF_CODE));
1254 case LFUN_CHANGES_MERGE:
1255 case LFUN_CHANGE_NEXT:
1256 case LFUN_CHANGE_PREVIOUS:
1257 case LFUN_ALL_CHANGES_ACCEPT:
1258 case LFUN_ALL_CHANGES_REJECT:
1259 flag.setEnabled(buffer_.areChangesPresent());
1262 case LFUN_SCREEN_UP:
1263 case LFUN_SCREEN_DOWN:
1265 case LFUN_SCREEN_UP_SELECT:
1266 case LFUN_SCREEN_DOWN_SELECT:
1267 case LFUN_INSET_FORALL:
1268 flag.setEnabled(true);
1271 case LFUN_LAYOUT_TABULAR:
1272 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1276 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1279 case LFUN_LAYOUT_PARAGRAPH:
1280 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1283 case LFUN_BRANCH_ADD_INSERT:
1284 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1287 case LFUN_DIALOG_SHOW_NEW_INSET:
1288 // FIXME: this is wrong, but I do not understand the
1290 if (cur.inset().lyxCode() == CAPTION_CODE)
1291 return cur.inset().getStatus(cur, cmd, flag);
1292 // FIXME we should consider passthru paragraphs too.
1293 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1296 case LFUN_CITATION_INSERT: {
1297 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1298 // FIXME: This could turn in a recursive hell.
1299 // Shouldn't we use Buffer::getStatus() instead?
1300 flag.setEnabled(lyx::getStatus(fr).enabled());
1303 case LFUN_INSET_APPLY: {
1304 string const name = cmd.getArg(0);
1305 Inset * inset = editedInset(name);
1307 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1308 if (!inset->getStatus(cur, fr, flag)) {
1309 // Every inset is supposed to handle this
1310 LASSERT(false, break);
1313 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1314 flag = lyx::getStatus(fr);
1320 flag.setEnabled(cur.selection());
1331 Inset * BufferView::editedInset(string const & name) const
1333 map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1334 return it == d->edited_insets_.end() ? nullptr : it->second;
1338 void BufferView::editInset(string const & name, Inset * inset)
1341 d->edited_insets_[name] = inset;
1343 d->edited_insets_.erase(name);
1347 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1349 LYXERR(Debug::ACTION, "BufferView::dispatch: cmd: " << cmd);
1351 string const argument = to_utf8(cmd.argument());
1352 Cursor & cur = d->cursor_;
1355 // Don't dispatch function that does not apply to internal buffers.
1356 if (buffer_.isInternal()
1357 && lyxaction.funcHasFlag(cmd.action(), LyXAction::NoInternal))
1360 // We'll set this back to false if need be.
1361 bool dispatched = true;
1362 buffer_.undo().beginUndoGroup();
1364 FuncCode const act = cmd.action();
1367 case LFUN_BUFFER_PARAMS_APPLY: {
1368 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
1369 cur.recordUndoBufferParams();
1370 istringstream ss(to_utf8(cmd.argument()));
1373 int const unknown_tokens = buffer_.readHeader(lex);
1374 if (unknown_tokens != 0) {
1375 LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1376 << unknown_tokens << " unknown token"
1377 << (unknown_tokens == 1 ? "" : "s"));
1379 updateDocumentClass(olddc);
1381 // We are most certainly here because of a change in the document
1382 // It is then better to make sure that all dialogs are in sync with
1383 // current document settings.
1384 dr.screenUpdate(Update::Force | Update::FitCursor);
1385 dr.forceBufferUpdate();
1389 case LFUN_LAYOUT_MODULES_CLEAR: {
1390 // FIXME: this modifies the document in cap::switchBetweenClasses
1391 // without calling recordUndo. Fix this before using
1392 // recordUndoBufferParams().
1393 cur.recordUndoFullBuffer();
1394 buffer_.params().clearLayoutModules();
1395 makeDocumentClass();
1396 dr.screenUpdate(Update::Force);
1397 dr.forceBufferUpdate();
1401 case LFUN_LAYOUT_MODULE_ADD: {
1402 BufferParams const & params = buffer_.params();
1403 if (!params.layoutModuleCanBeAdded(argument)) {
1404 LYXERR0("Module `" << argument <<
1405 "' cannot be added due to failed requirements or "
1406 "conflicts with installed modules.");
1409 // FIXME: this modifies the document in cap::switchBetweenClasses
1410 // without calling recordUndo. Fix this before using
1411 // recordUndoBufferParams().
1412 cur.recordUndoFullBuffer();
1413 buffer_.params().addLayoutModule(argument);
1414 makeDocumentClass();
1415 dr.screenUpdate(Update::Force);
1416 dr.forceBufferUpdate();
1420 case LFUN_TEXTCLASS_APPLY: {
1421 // since this shortcircuits, the second call is made only if
1423 bool const success =
1424 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1425 LayoutFileList::get().load(argument, buffer_.filePath());
1427 docstring s = bformat(_("The document class `%1$s' "
1428 "could not be loaded."), from_utf8(argument));
1429 frontend::Alert::error(_("Could not load class"), s);
1433 LayoutFile const * old_layout = buffer_.params().baseClass();
1434 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1436 if (old_layout == new_layout)
1440 // Save the old, possibly modular, layout for use in conversion.
1441 // FIXME: this modifies the document in cap::switchBetweenClasses
1442 // without calling recordUndo. Fix this before using
1443 // recordUndoBufferParams().
1444 cur.recordUndoFullBuffer();
1445 buffer_.params().setBaseClass(argument, buffer_.layoutPos());
1446 makeDocumentClass();
1447 dr.screenUpdate(Update::Force);
1448 dr.forceBufferUpdate();
1452 case LFUN_TEXTCLASS_LOAD: {
1453 // since this shortcircuits, the second call is made only if
1455 bool const success =
1456 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1457 LayoutFileList::get().load(argument, buffer_.filePath());
1459 docstring s = bformat(_("The document class `%1$s' "
1460 "could not be loaded."), from_utf8(argument));
1461 frontend::Alert::error(_("Could not load class"), s);
1466 case LFUN_LAYOUT_RELOAD: {
1467 LayoutFileIndex bc = buffer_.params().baseClassID();
1468 LayoutFileList::get().reset(bc);
1469 buffer_.params().setBaseClass(bc, buffer_.layoutPos());
1470 makeDocumentClass();
1471 dr.screenUpdate(Update::Force);
1472 dr.forceBufferUpdate();
1477 dr.setMessage(_("Undo"));
1478 cur.clearSelection();
1479 // We need to find out if the bibliography information
1480 // has changed. See bug #11055.
1481 // So these should not be references...
1482 string const engine = buffer().params().citeEngine();
1483 CiteEngineType const enginetype = buffer().params().citeEngineType();
1484 if (!cur.undoAction())
1485 dr.setMessage(_("No further undo information"));
1487 dr.screenUpdate(Update::Force | Update::FitCursor);
1488 dr.forceBufferUpdate();
1489 resetInlineCompletionPos();
1490 if (buffer().params().citeEngine() != engine ||
1491 buffer().params().citeEngineType() != enginetype)
1492 buffer().invalidateCiteLabels();
1498 dr.setMessage(_("Redo"));
1499 cur.clearSelection();
1500 // We need to find out if the bibliography information
1501 // has changed. See bug #11055.
1502 // So these should not be references...
1503 string const engine = buffer().params().citeEngine();
1504 CiteEngineType const enginetype = buffer().params().citeEngineType();
1505 if (!cur.redoAction())
1506 dr.setMessage(_("No further redo information"));
1508 dr.screenUpdate(Update::Force | Update::FitCursor);
1509 dr.forceBufferUpdate();
1510 resetInlineCompletionPos();
1511 if (buffer().params().citeEngine() != engine ||
1512 buffer().params().citeEngineType() != enginetype)
1513 buffer().invalidateCiteLabels();
1518 case LFUN_FONT_STATE:
1519 dr.setMessage(cur.currentState(false));
1522 case LFUN_BOOKMARK_SAVE:
1523 dr.screenUpdate(Update::Force);
1524 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1527 case LFUN_LABEL_GOTO: {
1528 docstring label = cmd.argument();
1529 if (label.empty()) {
1531 getInsetByCode<InsetRef>(cur, REF_CODE);
1533 label = inset->getParam("reference");
1534 // persistent=false: use temp_bookmark
1538 if (!label.empty()) {
1540 // at the moment, this is redundant, since gotoLabel will
1541 // eventually call LFUN_PARAGRAPH_GOTO, but it seems best
1543 dr.screenUpdate(Update::Force | Update::FitCursor);
1545 InsetMathRef * minset =
1546 getInsetByCode<InsetMathRef>(cur, MATH_REF_CODE);
1548 lyx::dispatch(FuncRequest(LFUN_LABEL_GOTO,
1549 minset->getTarget()));
1554 case LFUN_PARAGRAPH_GOTO: {
1555 int const id = convert<int>(cmd.getArg(0));
1556 pos_type const pos = convert<int>(cmd.getArg(1));
1559 string const str_id_end = cmd.getArg(2);
1560 string const str_pos_end = cmd.getArg(3);
1562 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1563 b = theBufferList().next(b)) {
1566 curs.setCursor(b->getParFromID(id));
1568 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1572 LYXERR(Debug::INFO, "Paragraph " << curs.paragraph().id()
1573 << " found in buffer `"
1574 << b->absFileName() << "'.");
1576 if (b == &buffer_) {
1578 if (str_id_end.empty() || str_pos_end.empty()) {
1581 mouseSetCursor(curs);
1584 int const id_end = convert<int>(str_id_end);
1585 pos_type const pos_end = convert<int>(str_pos_end);
1586 success = setCursorFromEntries({id, pos},
1589 if (success && scrollToCursor(d->cursor_, false, true))
1590 dr.screenUpdate(Update::Force);
1592 // Switch to other buffer view and resend cmd
1593 lyx::dispatch(FuncRequest(
1594 LFUN_BUFFER_SWITCH, b->absFileName()));
1602 case LFUN_NOTE_NEXT:
1603 if (gotoInset(this, { NOTE_CODE }, false))
1604 dr.screenUpdate(Update::Force);
1607 case LFUN_REFERENCE_NEXT: {
1608 if (gotoInset(this, { LABEL_CODE, REF_CODE }, true))
1609 dr.screenUpdate(Update::Force);
1613 case LFUN_CHANGE_NEXT:
1614 findNextChange(this);
1615 if (cur.inset().isTable())
1616 // In tables, there might be whole changed rows or columns
1618 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1619 dr.screenUpdate(Update::Force | Update::FitCursor);
1622 case LFUN_CHANGE_PREVIOUS:
1623 findPreviousChange(this);
1624 if (cur.inset().isTable())
1625 // In tables, there might be whole changed rows or columns
1627 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1628 dr.screenUpdate(Update::Force | Update::FitCursor);
1631 case LFUN_CHANGES_MERGE:
1632 if (findNextChange(this) || findPreviousChange(this)) {
1633 dr.screenUpdate(Update::Force | Update::FitCursor);
1634 dr.forceBufferUpdate();
1635 showDialog("changes");
1639 case LFUN_ALL_CHANGES_ACCEPT: {
1640 // select complete document
1642 cur.selHandle(true);
1643 buffer_.text().cursorBottom(cur);
1644 // accept everything in a single step to support atomic undo
1645 // temporarily disable track changes in order to end with really
1646 // no new (e.g., DPSM-caused) changes (see #7487)
1647 bool const track = buffer_.params().track_changes;
1648 buffer_.params().track_changes = false;
1649 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1650 buffer_.params().track_changes = track;
1652 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1653 dr.screenUpdate(Update::Force | Update::FitCursor);
1654 dr.forceBufferUpdate();
1658 case LFUN_ALL_CHANGES_REJECT: {
1659 // select complete document
1661 cur.selHandle(true);
1662 buffer_.text().cursorBottom(cur);
1663 // reject everything in a single step to support atomic undo
1664 // temporarily disable track changes in order to end with really
1665 // no new (e.g., DPSM-caused) changes (see #7487)
1666 bool const track = buffer_.params().track_changes;
1667 buffer_.params().track_changes = false;
1668 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1669 buffer_.params().track_changes = track;
1671 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1672 dr.screenUpdate(Update::Force | Update::FitCursor);
1673 dr.forceBufferUpdate();
1677 case LFUN_WORD_FIND_FORWARD:
1678 case LFUN_WORD_FIND_BACKWARD: {
1679 docstring searched_string;
1681 if (!cmd.argument().empty()) {
1682 setSearchRequestCache(cmd.argument());
1683 searched_string = cmd.argument();
1685 searched_string = searchRequestCache();
1688 if (searched_string.empty())
1691 docstring const data =
1692 find2string(searched_string, false, false,
1693 act == LFUN_WORD_FIND_FORWARD, false, false, false);
1694 bool found = lyxfind(this, FuncRequest(LFUN_WORD_FIND, data));
1696 dr.screenUpdate(Update::Force | Update::FitCursor);
1698 dr.setMessage(_("Search string not found!"));
1702 case LFUN_WORD_FIND: {
1703 docstring arg = cmd.argument();
1705 arg = searchRequestCache();
1707 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1710 if (lyxfind(this, FuncRequest(act, arg)))
1711 dr.screenUpdate(Update::Force | Update::FitCursor);
1713 dr.setMessage(_("Search string not found!"));
1715 setSearchRequestCache(arg);
1719 case LFUN_SEARCH_STRING_SET: {
1720 docstring pattern = cmd.argument();
1721 if (!pattern.empty()) {
1722 setSearchRequestCache(pattern);
1725 if (cur.selection())
1726 pattern = cur.selectionAsString(false);
1727 else if (!cur.inTexted())
1728 break; // not suitable for selectWord at cursor
1730 pos_type spos = cur.pos();
1731 cur.innerText()->selectWord(cur, WHOLE_WORD);
1732 pattern = cur.selectionAsString(false);
1733 cur.selection(false);
1736 setSearchRequestCache(pattern);
1740 case LFUN_WORD_REPLACE: {
1741 if (lyxreplace(this, cmd)) {
1742 dr.forceBufferUpdate();
1743 dr.screenUpdate(Update::Force | Update::FitCursor);
1746 dr.setMessage(_("Search string not found!"));
1750 case LFUN_WORD_FINDADV: {
1751 FindAndReplaceOptions opt;
1752 istringstream iss(to_utf8(cmd.argument()));
1754 if (findAdv(this, opt)) {
1755 dr.screenUpdate(Update::Force | Update::FitCursor);
1765 case LFUN_INDEX_TAG_ALL: {
1766 Inset * ins = cur.nextInset();
1767 if (!ins || ins->lyxCode() != INDEX_CODE)
1768 // not at index inset
1771 // clone the index inset
1773 new InsetIndex(static_cast<InsetIndex &>(*cur.nextInset()));
1774 // In order to avoid duplication, we compare the
1775 // LaTeX output if we find another index inset after
1777 odocstringstream oilatex;
1778 otexstream oits(oilatex);
1779 OutputParams rp(&cur.buffer()->params().encoding());
1780 ins->latex(oits, rp);
1781 cap::copyInsetToTemp(cur, cins);
1783 // move backwards into preceding word
1784 // skip over other index insets
1785 cur.backwardPosIgnoreCollapsed();
1787 if (cur.inset().lyxCode() == INDEX_CODE)
1789 else if (cur.prevInset() && cur.prevInset()->lyxCode() == INDEX_CODE)
1790 cur.backwardPosIgnoreCollapsed();
1794 if (!cur.inTexted()) {
1795 // Nothing to do here.
1796 setCursorFromInset(ins);
1799 // Get word or selection
1800 cur.text()->selectWord(cur, WHOLE_WORD);
1801 docstring const searched_string = cur.selectionAsString(false);
1802 // Start from the beginning
1803 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
1804 while (findOne(this, searched_string,
1805 false,// case sensitive
1806 true,// match whole word only
1808 false,//find deleted
1812 false// only selection
1814 cur.clearSelection();
1815 Inset * ains = cur.nextInset();
1816 if (ains && ains->lyxCode() == INDEX_CODE) {
1817 // We have an index inset.
1818 // Check whether it has the same
1819 // LaTeX content and move on if so.
1820 odocstringstream filatex;
1821 otexstream fits(filatex);
1822 ains->latex(fits, rp);
1823 if (oilatex.str() == filatex.str())
1826 // Paste the inset and possibly continue
1827 cap::pasteFromTemp(cursor(), cursor().buffer()->errorList("Paste"));
1829 // Go back to start position.
1830 setCursorFromInset(ins);
1831 dr.screenUpdate(cur.result().screenUpdate());
1832 if (cur.result().needBufferUpdate())
1833 dr.forceBufferUpdate();
1838 cur.clearSelection();
1839 dr.setMessage(from_utf8(N_("Mark off")));
1843 cur.clearSelection();
1845 dr.setMessage(from_utf8(N_("Mark on")));
1848 case LFUN_MARK_TOGGLE:
1849 cur.selection(false);
1852 dr.setMessage(from_utf8(N_("Mark removed")));
1855 dr.setMessage(from_utf8(N_("Mark set")));
1860 case LFUN_SCREEN_SHOW_CURSOR:
1864 case LFUN_SCREEN_RECENTER:
1868 case LFUN_BIBTEX_DATABASE_ADD: {
1869 Cursor tmpcur = cur;
1870 findInset(tmpcur, { BIBTEX_CODE }, false);
1871 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1874 if (inset->addDatabase(cmd.argument()))
1875 dr.forceBufferUpdate();
1880 case LFUN_BIBTEX_DATABASE_DEL: {
1881 Cursor tmpcur = cur;
1882 findInset(tmpcur, { BIBTEX_CODE }, false);
1883 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1886 if (inset->delDatabase(cmd.argument()))
1887 dr.forceBufferUpdate();
1892 case LFUN_GRAPHICS_UNIFY: {
1894 cur.recordUndoFullBuffer();
1896 DocIterator from, to;
1897 from = cur.selectionBegin();
1898 to = cur.selectionEnd();
1900 string const newId = cmd.getArg(0);
1901 bool fetchId = newId.empty(); //if we wait for groupId from first graphics inset
1903 InsetGraphicsParams grp_par;
1905 InsetGraphics::string2params(graphics::getGroupParams(buffer_, newId), buffer_, grp_par);
1907 if (!from.nextInset()) //move to closest inset
1908 from.forwardInset();
1910 while (!from.empty() && from < to) {
1911 Inset * inset = from.nextInset();
1914 InsetGraphics * ig = inset->asInsetGraphics();
1916 InsetGraphicsParams inspar = ig->getParams();
1921 grp_par.filename = inspar.filename;
1922 ig->setParams(grp_par);
1925 from.forwardInset();
1927 dr.screenUpdate(Update::Force); //needed if triggered from context menu
1931 case LFUN_STATISTICS: {
1932 DocIterator from, to;
1933 if (cur.selection()) {
1934 from = cur.selectionBegin();
1935 to = cur.selectionEnd();
1937 from = doc_iterator_begin(&buffer_);
1938 to = doc_iterator_end(&buffer_);
1940 buffer_.updateStatistics(from, to);
1941 int const words = buffer_.wordCount();
1942 int const chars = buffer_.charCount(false);
1943 int const chars_blanks = buffer_.charCount(true);
1945 if (cur.selection())
1946 message = _("Statistics for the selection:");
1948 message = _("Statistics for the document:");
1951 message += bformat(_("%1$d words"), words);
1953 message += _("One word");
1955 if (chars_blanks != 1)
1956 message += bformat(_("%1$d characters"), chars_blanks);
1958 message += _("One character");
1961 message += bformat(_("%1$d characters (no blanks)"), chars);
1963 message += _("One character (no blanks)");
1965 Alert::information(_("Statistics"), message);
1969 case LFUN_SCREEN_UP:
1970 case LFUN_SCREEN_DOWN: {
1971 Point p = getPos(cur);
1972 // This code has been commented out to enable to scroll down a
1973 // document, even if there are large insets in it (see bug #5465).
1974 /*if (p.y_ < 0 || p.y_ > height_) {
1975 // The cursor is off-screen so recenter before proceeding.
1979 int const scrolled = scroll(act == LFUN_SCREEN_UP
1980 ? -height_ : height_);
1981 if (act == LFUN_SCREEN_UP && scrolled > -height_)
1983 if (act == LFUN_SCREEN_DOWN && scrolled < height_)
1984 p = Point(width_, height_);
1985 bool const in_texted = cur.inTexted();
1986 cur.setCursor(doc_iterator_begin(cur.buffer()));
1987 cur.selHandle(false);
1988 // Force an immediate computation of metrics because we need it below
1990 processUpdateFlags(Update::Force);
1992 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1993 true, act == LFUN_SCREEN_UP);
1994 //FIXME: what to do with cur.x_target()?
1995 bool update = in_texted && cur.bv().checkDepm(cur, old);
1998 if (update || cur.mark())
1999 dr.screenUpdate(Update::Force | Update::FitCursor);
2001 dr.forceBufferUpdate();
2006 string const scroll_type = cmd.getArg(0);
2007 int scroll_step = 0;
2008 if (scroll_type == "line")
2009 scroll_step = d->scrollbarParameters_.single_step;
2010 else if (scroll_type == "page")
2011 scroll_step = d->scrollbarParameters_.page_step;
2014 string const scroll_quantity = cmd.getArg(1);
2015 if (scroll_quantity == "up")
2016 scrollUp(scroll_step);
2017 else if (scroll_quantity == "down")
2018 scrollDown(scroll_step);
2020 int const scroll_value = convert<int>(scroll_quantity);
2022 scroll(scroll_step * scroll_value);
2024 dr.screenUpdate(Update::ForceDraw);
2025 dr.forceBufferUpdate();
2029 case LFUN_SCREEN_UP_SELECT: {
2030 // FIXME: why is the algorithm different from LFUN_SCREEN_UP?
2031 cur.selHandle(true);
2032 if (isTopScreen()) {
2033 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
2037 int y = getPos(cur).y_;
2038 int const ymin = y - height_ + defaultRowHeight();
2039 while (y > ymin && cur.up())
2043 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
2047 case LFUN_SCREEN_DOWN_SELECT: {
2048 // FIXME: why is the algorithm different from LFUN_SCREEN_DOWN?
2049 cur.selHandle(true);
2050 if (isBottomScreen()) {
2051 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
2055 int y = getPos(cur).y_;
2056 int const ymax = y + height_ - defaultRowHeight();
2057 while (y < ymax && cur.down())
2061 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
2066 case LFUN_INSET_SELECT_ALL: {
2067 // true if all cells are selected
2068 bool const all_selected = cur.depth() > 1
2069 && cur.selBegin().at_begin()
2070 && cur.selEnd().at_end();
2071 // true if some cells are selected
2072 bool const cells_selected = cur.depth() > 1
2073 && cur.selBegin().at_cell_begin()
2074 && cur.selEnd().at_cell_end();
2075 if (all_selected || (cells_selected && !cur.inset().isTable())) {
2076 // All the contents of the inset if selected, or only at
2077 // least one cell but inset is not a table.
2078 // Select the inset from outside.
2081 cur.selection(true);
2083 } else if (cells_selected) {
2084 // At least one complete cell is selected and inset is a table.
2090 cur.selection(true);
2091 cur.idx() = cur.lastidx();
2092 cur.pit() = cur.lastpit();
2093 cur.pos() = cur.lastpos();
2095 // select current cell
2099 cur.selection(true);
2100 cur.pit() = cur.lastpit();
2101 cur.pos() = cur.lastpos();
2103 cur.setCurrentFont();
2104 dr.screenUpdate(Update::Force);
2109 case LFUN_UNICODE_INSERT: {
2110 if (cmd.argument().empty())
2113 FuncCode code = cur.inset().currentMode() == Inset::MATH_MODE ?
2114 LFUN_MATH_INSERT : LFUN_SELF_INSERT;
2117 docstring const arg = from_utf8(cmd.getArg(i));
2121 LYXERR0("Not a hexstring: " << arg);
2125 char_type c = hexToInt(arg);
2126 if (c >= 32 && c < 0x10ffff) {
2127 LYXERR(Debug::KEY, "Inserting c: " << c);
2128 lyx::dispatch(FuncRequest(code, docstring(1, c)));
2136 // This would be in Buffer class if only Cursor did not
2137 // require a bufferview
2138 case LFUN_INSET_FORALL: {
2139 docstring const name = from_utf8(cmd.getArg(0));
2140 string const commandstr = cmd.getLongArg(1);
2141 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
2143 // an arbitrary number to limit number of iterations
2144 const int max_iter = 100000;
2146 Cursor & bvcur = d->cursor_;
2147 Cursor const savecur = bvcur;
2149 if (!bvcur.nextInset())
2150 bvcur.forwardInset();
2151 bvcur.beginUndoGroup();
2152 while(bvcur && iterations < max_iter) {
2153 Inset * const ins = bvcur.nextInset();
2156 docstring insname = ins->layoutName();
2157 while (!insname.empty()) {
2158 if (insname == name || name == from_utf8("*")) {
2159 lyx::dispatch(fr, dr);
2160 // we do not want to remember selection here
2161 bvcur.clearSelection();
2165 size_t const i = insname.rfind(':');
2166 if (i == string::npos)
2168 insname = insname.substr(0, i);
2170 // if we did not delete the inset, skip it
2171 if (!bvcur.nextInset() || bvcur.nextInset() == ins)
2172 bvcur.forwardInset();
2175 bvcur.fixIfBroken();
2176 /** This is a dummy undo record only to remember the cursor
2177 * that has just been set; this will be used on a redo action
2178 * (see ticket #10097)
2180 * FIXME: a better fix would be to have a way to set the
2181 * cursor value directly, but I am not sure it is worth it.
2184 bvcur.endUndoGroup();
2185 dr.screenUpdate(Update::Force);
2186 dr.forceBufferUpdate();
2188 if (iterations >= max_iter) {
2190 dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
2192 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
2197 case LFUN_BRANCH_ADD_INSERT: {
2198 docstring branch_name = from_utf8(cmd.getArg(0));
2199 if (branch_name.empty())
2200 if (!Alert::askForText(branch_name, _("Branch name")) ||
2201 branch_name.empty())
2204 DispatchResult drtmp;
2205 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
2206 if (drtmp.error()) {
2207 Alert::warning(_("Branch already exists"), drtmp.message());
2210 docstring const sep = buffer_.params().branchlist().separator();
2211 for (docstring const & branch : getVectorFromString(branch_name, sep))
2212 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch));
2216 case LFUN_KEYMAP_OFF:
2217 getIntl().keyMapOn(false);
2220 case LFUN_KEYMAP_PRIMARY:
2221 getIntl().keyMapPrim();
2224 case LFUN_KEYMAP_SECONDARY:
2225 getIntl().keyMapSec();
2228 case LFUN_KEYMAP_TOGGLE:
2229 getIntl().toggleKeyMap();
2232 case LFUN_DIALOG_SHOW_NEW_INSET: {
2233 string const name = cmd.getArg(0);
2234 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2235 if (decodeInsetParam(name, data, buffer_))
2236 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
2238 lyxerr << "Inset type '" << name <<
2239 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
2243 case LFUN_CITATION_INSERT: {
2244 if (argument.empty()) {
2245 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
2248 // we can have one optional argument, delimited by '|'
2249 // citation-insert <key>|<text_before>
2250 // this should be enhanced to also support text_after
2251 // and citation style
2252 string arg = argument;
2254 if (contains(argument, "|")) {
2255 arg = token(argument, '|', 0);
2256 opt1 = token(argument, '|', 1);
2259 // if our cursor is directly in front of or behind a citation inset,
2260 // we will instead add the new key to it.
2261 Inset * inset = cur.nextInset();
2262 if (!inset || inset->lyxCode() != CITE_CODE)
2263 inset = cur.prevInset();
2264 if (inset && inset->lyxCode() == CITE_CODE) {
2265 InsetCitation * icite = static_cast<InsetCitation *>(inset);
2266 if (icite->addKey(arg)) {
2267 dr.forceBufferUpdate();
2268 dr.screenUpdate(Update::FitCursor | Update::SinglePar);
2270 LYXERR0("Discarding optional argument to citation-insert.");
2275 InsetCommandParams icp(CITE_CODE);
2276 icp["key"] = from_utf8(arg);
2278 icp["before"] = from_utf8(opt1);
2280 from_ascii(InsetCitation::last_literal ? "true" : "false");
2281 string icstr = InsetCommand::params2string(icp);
2282 FuncRequest fr(LFUN_INSET_INSERT, icstr);
2287 case LFUN_INSET_APPLY: {
2288 string const name = cmd.getArg(0);
2289 Inset * inset = editedInset(name);
2291 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
2295 // put cursor in front of inset.
2296 if (!setCursorFromInset(inset)) {
2297 LASSERT(false, break);
2300 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
2301 inset->dispatch(cur, fr);
2302 dr.screenUpdate(cur.result().screenUpdate());
2303 if (cur.result().needBufferUpdate())
2304 dr.forceBufferUpdate();
2309 // The change of language of buffer belongs to the Buffer class.
2310 // We have to do it here because we need a cursor for Undo.
2311 // When Undo::recordUndoBufferParams() is implemented someday
2312 // LFUN_BUFFER_LANGUAGE should be handled by the Buffer class.
2313 case LFUN_BUFFER_LANGUAGE: {
2314 Language const * oldL = buffer_.params().language;
2315 Language const * newL = languages.getLanguage(argument);
2316 if (!newL || oldL == newL)
2318 if (oldL->rightToLeft() == newL->rightToLeft()) {
2319 cur.recordUndoFullBuffer();
2320 buffer_.changeLanguage(oldL, newL);
2321 cur.setCurrentFont();
2322 dr.forceBufferUpdate();
2327 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2328 case LFUN_FILE_INSERT_PLAINTEXT: {
2329 bool const as_paragraph = (act == LFUN_FILE_INSERT_PLAINTEXT_PARA);
2330 string const fname = to_utf8(cmd.argument());
2331 if (!FileName::isAbsolute(fname))
2332 dr.setMessage(_("Absolute filename expected."));
2334 insertPlaintextFile(FileName(fname), as_paragraph);
2339 // With multi-cell table content, we pass down to the inset
2340 if (cur.inTexted() && cur.selection()
2341 && cur.selectionBegin().idx() != cur.selectionEnd().idx()) {
2342 buffer_.dispatch(cmd, dr);
2343 dispatched = dr.dispatched();
2346 cap::copySelection(cur);
2347 cur.message(_("Copy"));
2351 // OK, so try the Buffer itself...
2352 buffer_.dispatch(cmd, dr);
2353 dispatched = dr.dispatched();
2357 buffer_.undo().endUndoGroup();
2358 dr.dispatched(dispatched);
2360 // NOTE: The code below is copied from Cursor::dispatch. If you
2361 // need to modify this, please update the other one too.
2363 // notify insets we just entered/left
2364 if (cursor() != old) {
2365 old.beginUndoGroup();
2367 bool badcursor = notifyCursorLeavesOrEnters(old, cursor());
2369 cursor().fixIfBroken();
2370 resetInlineCompletionPos();
2377 docstring BufferView::requestSelection()
2379 Cursor & cur = d->cursor_;
2381 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
2382 if (!cur.selection()) {
2383 d->xsel_cache_.set = false;
2387 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
2388 if (!d->xsel_cache_.set ||
2389 cur.top() != d->xsel_cache_.cursor ||
2390 cur.realAnchor().top() != d->xsel_cache_.anchor)
2392 d->xsel_cache_.cursor = cur.top();
2393 d->xsel_cache_.anchor = cur.realAnchor().top();
2394 d->xsel_cache_.set = cur.selection();
2395 return cur.selectionAsString(false);
2401 void BufferView::clearSelection()
2403 d->cursor_.clearSelection();
2404 // Clear the selection buffer. Otherwise a subsequent
2405 // middle-mouse-button paste would use the selection buffer,
2406 // not the more current external selection.
2407 cap::clearSelection();
2408 d->xsel_cache_.set = false;
2409 // The buffer did not really change, but this causes the
2410 // redraw we need because we cleared the selection above.
2411 buffer_.changed(false);
2415 void BufferView::resize(int width, int height)
2417 // Update from work area
2421 // Clear the paragraph height cache.
2422 d->par_height_.clear();
2423 // Redo the metrics.
2428 Inset const * BufferView::getCoveringInset(Text const & text,
2431 TextMetrics & tm = d->text_metrics_[&text];
2432 Inset * inset = tm.checkInsetHit(x, y);
2436 if (!inset->descendable(*this))
2437 // No need to go further down if the inset is not
2441 size_t cell_number = inset->nargs();
2442 // Check all the inner cell.
2443 for (size_t i = 0; i != cell_number; ++i) {
2444 Text const * inner_text = inset->getText(i);
2447 Inset const * inset_deeper =
2448 getCoveringInset(*inner_text, x, y);
2450 return inset_deeper;
2458 Inset const * BufferView::clickableMathInset(InsetMathNest const * inset,
2459 CoordCache::Insets const & inset_cache, int x, int y) const
2461 for (size_t i = 0; i < inset->nargs(); ++i) {
2462 MathData const & ar = inset->cell(i);
2463 for (size_t j = 0; j < ar.size(); ++j) {
2464 string const name = lyxerr.debugging(Debug::MATHED)
2465 ? insetName(ar[j].nucleus()->lyxCode())
2467 LYXERR(Debug::MATHED, "Checking inset: " << name);
2468 if (ar[j].nucleus()->clickable(*this, x, y)) {
2469 if (inset_cache.covers(ar[j].nucleus(), x, y)) {
2470 LYXERR(Debug::MATHED, "Clickable inset: "
2472 return ar[j].nucleus();
2475 InsetMathNest const * imn =
2476 ar[j].nucleus()->asNestInset();
2478 Inset const * inner =
2479 clickableMathInset(imn, inset_cache, x, y);
2489 void BufferView::updateHoveredInset() const
2491 // Get inset under mouse, if there is one.
2492 int const x = d->mouse_position_cache_.x_;
2493 int const y = d->mouse_position_cache_.y_;
2494 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
2495 if (covering_inset && covering_inset->asInsetMath()) {
2496 Inset const * inner_inset = clickableMathInset(
2497 covering_inset->asInsetMath()->asNestInset(),
2498 coordCache().getInsets(), x, y);
2500 covering_inset = inner_inset;
2503 d->clickable_inset_ = covering_inset && covering_inset->clickable(*this, x, y);
2505 if (covering_inset == d->last_inset_)
2506 // Same inset, no need to do anything...
2509 bool need_redraw = false;
2510 if (d->last_inset_) {
2511 // Remove the hint on the last hovered inset (if any).
2512 need_redraw |= d->last_inset_->setMouseHover(this, false);
2513 d->last_inset_ = nullptr;
2516 if (covering_inset && covering_inset->setMouseHover(this, true)) {
2518 // Only the insets that accept the hover state, do
2519 // clear the last_inset_, so only set the last_inset_
2520 // member if the hovered setting is accepted.
2521 d->last_inset_ = covering_inset;
2525 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
2526 << d->mouse_position_cache_.x_ << ", "
2527 << d->mouse_position_cache_.y_ << ")");
2529 d->update_strategy_ = DecorationUpdate;
2531 // This event (moving without mouse click) is not passed further.
2532 // This should be changed if it is further utilized.
2533 buffer_.changed(false);
2538 void BufferView::clearLastInset(Inset * inset) const
2540 if (d->last_inset_ != inset) {
2541 LYXERR0("Wrong last_inset!");
2544 d->last_inset_ = nullptr;
2548 bool BufferView::mouseSelecting() const
2550 return d->mouse_selecting_;
2554 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
2556 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
2558 // This is only called for mouse related events including
2559 // LFUN_FILE_OPEN generated by drag-and-drop.
2560 FuncRequest cmd = cmd0;
2562 Cursor old = cursor();
2564 cur.push(buffer_.inset());
2565 cur.selection(d->cursor_.selection());
2567 // Either the inset under the cursor or the
2568 // surrounding Text will handle this event.
2570 // make sure we stay within the screen...
2571 cmd.set_y(min(max(cmd.y(), -1), height_));
2573 d->mouse_position_cache_.x_ = cmd.x();
2574 d->mouse_position_cache_.y_ = cmd.y();
2576 d->mouse_selecting_ =
2577 cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::button1;
2579 if (cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
2580 updateHoveredInset();
2584 // Build temporary cursor.
2585 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x(), cmd.y());
2587 // If inset is not editable, cur.pos() might point behind the
2588 // inset (depending on cmd.x(), cmd.y()). This is needed for
2589 // editing to fix bug 9628, but e.g. the context menu needs a
2590 // cursor in front of the inset.
2591 if ((inset->hasSettings() || !inset->contextMenuName().empty()
2592 || inset->lyxCode() == SEPARATOR_CODE) &&
2593 cur.nextInset() != inset && cur.prevInset() == inset)
2595 } else if (cur.inTexted() && cur.pos()
2596 && cur.paragraph().isEnvSeparator(cur.pos() - 1)) {
2597 // Always place cursor in front of a separator inset.
2601 // Put anchor at the same position.
2604 cur.beginUndoGroup();
2606 // Try to dispatch to an non-editable inset near this position
2607 // via the temp cursor. If the inset wishes to change the real
2608 // cursor it has to do so explicitly by using
2609 // cur.bv().cursor() = cur; (or similar)
2611 inset->dispatch(cur, cmd);
2613 // Now dispatch to the temporary cursor. If the real cursor should
2614 // be modified, the inset's dispatch has to do so explicitly.
2615 if (!inset || !cur.result().dispatched())
2618 // Notify left insets
2620 bool badcursor = old.fixIfBroken() || cur.fixIfBroken();
2621 badcursor = badcursor || notifyCursorLeavesOrEnters(old, cur);
2623 cursor().fixIfBroken();
2628 // Do we have a selection?
2629 theSelection().haveSelection(cursor().selection());
2631 if (cur.needBufferUpdate() || buffer().needUpdate()) {
2632 cur.clearBufferUpdate();
2633 buffer().updateBuffer();
2636 // If the command has been dispatched,
2637 if (cur.result().dispatched() || cur.result().screenUpdate())
2638 processUpdateFlags(cur.result().screenUpdate());
2642 int BufferView::minVisiblePart()
2644 return 2 * defaultRowHeight();
2648 int BufferView::scroll(int pixels)
2651 return scrollDown(pixels);
2653 return scrollUp(-pixels);
2658 int BufferView::scrollDown(int pixels)
2660 Text * text = &buffer_.text();
2661 TextMetrics & tm = d->text_metrics_[text];
2662 int const ymax = height_ + pixels;
2664 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2665 int bottom_pos = last.second->position() + last.second->descent();
2666 if (lyxrc.scroll_below_document)
2667 bottom_pos += height_ - minVisiblePart();
2668 if (last.first + 1 == int(text->paragraphs().size())) {
2669 if (bottom_pos <= height_)
2671 pixels = min(pixels, bottom_pos - height_);
2674 if (bottom_pos > ymax)
2676 tm.newParMetricsDown();
2678 d->anchor_ypos_ -= pixels;
2683 int BufferView::scrollUp(int pixels)
2685 Text * text = &buffer_.text();
2686 TextMetrics & tm = d->text_metrics_[text];
2687 int ymin = - pixels;
2689 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2690 int top_pos = first.second->position() - first.second->ascent();
2691 if (first.first == 0) {
2694 pixels = min(pixels, - top_pos);
2699 tm.newParMetricsUp();
2701 d->anchor_ypos_ += pixels;
2706 bool BufferView::setCursorFromRow(int row)
2708 TexRow::TextEntry start, end;
2709 tie(start,end) = buffer_.texrow().getEntriesFromRow(row);
2710 LYXERR(Debug::OUTFILE,
2711 "setCursorFromRow: for row " << row << ", TexRow has found "
2712 "start (id=" << start.id << ",pos=" << start.pos << "), "
2713 "end (id=" << end.id << ",pos=" << end.pos << ")");
2714 return setCursorFromEntries(start, end);
2718 bool BufferView::setCursorFromEntries(TexRow::TextEntry start,
2719 TexRow::TextEntry end)
2721 DocIterator dit_start, dit_end;
2722 tie(dit_start,dit_end) =
2723 TexRow::getDocIteratorsFromEntries(start, end, buffer_);
2726 // Setting selection start
2727 d->cursor_.clearSelection();
2728 setCursor(dit_start);
2729 // Setting selection end
2731 d->cursor_.resetAnchor();
2732 setCursorSelectionTo(dit_end);
2738 bool BufferView::setCursorFromInset(Inset const * inset)
2740 // are we already there?
2741 if (cursor().nextInset() == inset)
2744 // Inset is not at cursor position. Find it in the document.
2747 while (cur && cur.nextInset() != inset)
2758 void BufferView::gotoLabel(docstring const & label)
2761 bool have_inactive = false;
2762 for (Buffer const * buf : buffer().allRelatives()) {
2764 for (TocItem const & item : *buf->tocBackend().toc("label")) {
2765 if (label == item.str() && item.isOutput()) {
2766 lyx::dispatch(item.action());
2769 // If we find an inactive label, save it for the case
2770 // that no active one is there
2771 if (label == item.str() && !have_inactive) {
2772 have_inactive = true;
2773 action = item.action();
2777 // We only found an inactive label. Go there.
2779 lyx::dispatch(action);
2783 TextMetrics const & BufferView::textMetrics(Text const * t) const
2785 return const_cast<BufferView *>(this)->textMetrics(t);
2789 TextMetrics & BufferView::textMetrics(Text const * t)
2792 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
2793 if (tmc_it == d->text_metrics_.end()) {
2794 tmc_it = d->text_metrics_.emplace(std::piecewise_construct,
2795 std::forward_as_tuple(t),
2796 std::forward_as_tuple(this, const_cast<Text *>(t))).first;
2798 return tmc_it->second;
2802 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2805 return textMetrics(t).parMetrics(pit);
2809 int BufferView::workHeight() const
2815 void BufferView::setCursor(DocIterator const & dit)
2818 size_t const n = dit.depth();
2819 for (size_t i = 0; i < n; ++i)
2820 dit[i].inset().edit(d->cursor_, true);
2822 d->cursor_.setCursor(dit);
2823 d->cursor_.selection(false);
2824 d->cursor_.setCurrentFont();
2826 // It seems on general grounds as if this is probably needed, but
2827 // it is not yet clear.
2828 // See bug #7394 and r38388.
2829 // d->cursor.resetAnchor();
2833 void BufferView::setCursorSelectionTo(DocIterator const & dit)
2835 size_t const n = dit.depth();
2836 for (size_t i = 0; i < n; ++i)
2837 dit[i].inset().edit(d->cursor_, true);
2839 d->cursor_.selection(true);
2840 d->cursor_.setCursorSelectionTo(dit);
2841 d->cursor_.setCurrentFont();
2845 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2847 // Would be wrong to delete anything if we have a selection.
2848 if (cur.selection())
2851 bool need_anchor_change = false;
2852 bool changed = Text::deleteEmptyParagraphMechanism(cur, old,
2853 need_anchor_change);
2855 if (need_anchor_change)
2863 // we would rather not do this here, but it needs to be done before
2864 // the changed() signal is sent.
2865 buffer_.updateBuffer();
2867 buffer_.changed(true);
2872 bool BufferView::mouseSetCursor(Cursor & cur, bool const select)
2874 LASSERT(&cur.bv() == this, return false);
2877 // this event will clear selection so we save selection for
2878 // persistent selection
2879 cap::saveSelection(cursor());
2881 d->cursor_.macroModeClose();
2882 // If a macro has been finalized, the cursor might have been broken
2885 // Has the cursor just left the inset?
2886 bool const leftinset = (&d->cursor_.inset() != &cur.inset());
2888 d->cursor_.fixIfBroken();
2890 // do the dEPM magic if needed
2891 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2892 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2893 // the leftinset bool would not be necessary (badcursor instead).
2894 bool update = leftinset;
2897 d->cursor_.setSelection();
2898 d->cursor_.setCursorSelectionTo(cur);
2900 if (d->cursor_.inTexted())
2901 update |= checkDepm(cur, d->cursor_);
2902 d->cursor_.resetAnchor();
2903 d->cursor_.setCursor(cur);
2904 d->cursor_.clearSelection();
2906 d->cursor_.boundary(cur.boundary());
2907 d->cursor_.finishUndo();
2908 d->cursor_.setCurrentFont();
2910 cur.forceBufferUpdate();
2915 void BufferView::putSelectionAt(DocIterator const & cur,
2916 int length, bool backwards)
2918 d->cursor_.clearSelection();
2924 d->cursor_.pos() += length;
2925 d->cursor_.setSelection(d->cursor_, -length);
2927 d->cursor_.setSelection(d->cursor_, length);
2932 bool BufferView::selectIfEmpty(DocIterator & cur)
2934 if ((cur.inTexted() && !cur.paragraph().empty())
2935 || (cur.inMathed() && !cur.cell().empty()))
2938 pit_type const beg_pit = cur.pit();
2940 // The paragraph associated to this item isn't
2941 // the first one, so it can be selected
2944 // We have to resort to select the space between the
2945 // end of this item and the begin of the next one
2949 // If it is the only item in the document,
2950 // nothing can be selected
2953 pit_type const end_pit = cur.pit();
2954 pos_type const end_pos = cur.pos();
2955 d->cursor_.clearSelection();
2957 d->cursor_.setCursor(cur);
2958 d->cursor_.pit() = beg_pit;
2959 d->cursor_.pos() = 0;
2960 d->cursor_.selection(false);
2961 d->cursor_.resetAnchor();
2962 d->cursor_.pit() = end_pit;
2963 d->cursor_.pos() = end_pos;
2964 d->cursor_.setSelection();
2969 Cursor & BufferView::cursor()
2975 Cursor const & BufferView::cursor() const
2981 bool BufferView::singleParUpdate()
2983 Text & buftext = buffer_.text();
2984 pit_type const bottom_pit = d->cursor_.bottom().pit();
2985 TextMetrics & tm = textMetrics(&buftext);
2986 Dimension const old_dim = tm.parMetrics(bottom_pit).dim();
2988 // make sure inline completion pointer is ok
2989 if (d->inlineCompletionPos_.fixIfBroken())
2990 d->inlineCompletionPos_ = DocIterator();
2992 // In Single Paragraph mode, rebreak only
2993 // the (main text, not inset!) paragraph containing the cursor.
2994 // (if this paragraph contains insets etc., rebreaking will
2995 // recursively descend)
2996 tm.redoParagraph(bottom_pit);
2997 ParagraphMetrics & pm = tm.parMetrics(bottom_pit);
2998 if (pm.height() != old_dim.height()) {
2999 // Paragraph height has changed so we cannot proceed to
3000 // the singlePar optimisation.
3003 // Since position() points to the baseline of the first row, we
3004 // may have to update it. See ticket #11601 for an example where
3005 // the height does not change but the ascent does.
3006 pm.setPosition(pm.position() - old_dim.ascent() + pm.ascent());
3008 tm.updatePosCache(bottom_pit);
3010 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
3011 << " y2: " << pm.position() + pm.descent()
3012 << " pit: " << bottom_pit
3013 << " singlepar: 1");
3018 void BufferView::updateMetrics()
3020 updateMetrics(d->update_flags_);
3021 d->update_strategy_ = FullScreenUpdate;
3025 void BufferView::updateMetrics(Update::flags & update_flags)
3027 if (height_ == 0 || width_ == 0)
3030 Text & buftext = buffer_.text();
3031 pit_type const npit = int(buftext.paragraphs().size());
3033 // Clear out the position cache in case of full screen redraw,
3034 d->coord_cache_.clear();
3035 d->math_rows_.clear();
3037 // Clear out paragraph metrics to avoid having invalid metrics
3038 // in the cache from paragraphs not relayouted below
3039 // The complete text metrics will be redone.
3040 d->text_metrics_.clear();
3042 TextMetrics & tm = textMetrics(&buftext);
3044 // make sure inline completion pointer is ok
3045 if (d->inlineCompletionPos_.fixIfBroken())
3046 d->inlineCompletionPos_ = DocIterator();
3048 if (d->anchor_pit_ >= npit)
3049 // The anchor pit must have been deleted...
3050 d->anchor_pit_ = npit - 1;
3052 // Rebreak anchor paragraph.
3053 tm.redoParagraph(d->anchor_pit_);
3054 ParagraphMetrics & anchor_pm = tm.parMetrics(d->anchor_pit_);
3057 if (d->anchor_pit_ == 0) {
3058 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
3060 // Complete buffer visible? Then it's easy.
3061 if (scrollRange == 0)
3062 d->anchor_ypos_ = anchor_pm.ascent();
3064 // avoid empty space above the first row
3065 d->anchor_ypos_ = min(d->anchor_ypos_, anchor_pm.ascent());
3068 anchor_pm.setPosition(d->anchor_ypos_);
3069 tm.updatePosCache(d->anchor_pit_);
3071 LYXERR(Debug::PAINTING, "metrics: "
3072 << " anchor pit = " << d->anchor_pit_
3073 << " anchor ypos = " << d->anchor_ypos_);
3075 // Redo paragraphs above anchor if necessary.
3076 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
3077 // We are now just above the anchor paragraph.
3078 pit_type pit1 = d->anchor_pit_ - 1;
3079 for (; pit1 >= 0 && y1 >= 0; --pit1) {
3080 tm.redoParagraph(pit1);
3081 ParagraphMetrics & pm = tm.parMetrics(pit1);
3083 // Save the paragraph position in the cache.
3085 tm.updatePosCache(pit1);
3089 // Redo paragraphs below the anchor if necessary.
3090 int y2 = d->anchor_ypos_ + anchor_pm.descent();
3091 // We are now just below the anchor paragraph.
3092 pit_type pit2 = d->anchor_pit_ + 1;
3093 for (; pit2 < npit && y2 <= height_; ++pit2) {
3094 tm.redoParagraph(pit2);
3095 ParagraphMetrics & pm = tm.parMetrics(pit2);
3097 // Save the paragraph position in the cache.
3099 tm.updatePosCache(pit2);
3103 LYXERR(Debug::PAINTING, "Metrics: "
3104 << " anchor pit = " << d->anchor_pit_
3105 << " anchor ypos = " << d->anchor_ypos_
3108 << " pit1 = " << pit1
3109 << " pit2 = " << pit2);
3111 // metrics is done, full drawing is necessary now
3112 update_flags = (update_flags & ~Update::Force) | Update::ForceDraw;
3114 // Now update the positions of insets in the cache.
3117 if (lyxerr.debugging(Debug::WORKAREA)) {
3118 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
3119 d->coord_cache_.dump();
3124 void BufferView::updatePosCache()
3126 // this is the "nodraw" drawing stage: only set the positions of the
3127 // insets in metrics cache.
3128 frontend::NullPainter np;
3133 void BufferView::insertLyXFile(FileName const & fname, bool const ignorelang)
3135 LASSERT(d->cursor_.inTexted(), return);
3137 // Get absolute path of file and add ".lyx"
3138 // to the filename if necessary
3139 FileName filename = fileSearch(string(), fname.absFileName(), "lyx");
3141 docstring const disp_fn = makeDisplayPath(filename.absFileName());
3142 // emit message signal.
3143 message(bformat(_("Inserting document %1$s..."), disp_fn));
3146 Buffer buf(filename.absFileName(), false);
3147 if (buf.loadLyXFile() == Buffer::ReadSuccess) {
3148 ErrorList & el = buffer_.errorList("Parse");
3149 // Copy the inserted document error list into the current buffer one.
3150 el = buf.errorList("Parse");
3151 ParagraphList & pars = buf.paragraphs();
3153 // set main language of imported file to context language
3154 buf.changeLanguage(buf.language(), d->cursor_.getFont().language());
3155 buffer_.undo().recordUndo(d->cursor_);
3156 cap::pasteParagraphList(d->cursor_, pars,
3157 buf.params().documentClassPtr(),
3158 buf.params().authors(), el);
3159 res = _("Document %1$s inserted.");
3161 res = _("Could not insert document %1$s");
3164 buffer_.changed(true);
3165 // emit message signal.
3166 message(bformat(res, disp_fn));
3170 Point BufferView::coordOffset(DocIterator const & dit) const
3176 // Addup contribution of nested insets, from inside to outside,
3177 // keeping the outer paragraph for a special handling below
3178 for (size_t i = dit.depth() - 1; i >= 1; --i) {
3179 CursorSlice const & sl = dit[i];
3183 // get relative position inside sl.inset()
3184 sl.inset().cursorPos(*this, sl, dit.boundary() && (i + 1 == dit.depth()), xx, yy);
3186 // Make relative position inside of the edited inset relative to sl.inset()
3190 // In case of an RTL inset, the edited inset will be positioned to the left
3193 bool boundary_i = dit.boundary() && i + 1 == dit.depth();
3194 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
3199 // remember width for the case that sl.inset() is positioned in an RTL inset
3200 lastw = sl.inset().dimension(*this).wid;
3202 //lyxerr << "Cursor::getPos, i: "
3203 // << i << " x: " << xx << " y: " << y << endl;
3206 // Add contribution of initial rows of outermost paragraph
3207 CursorSlice const & sl = dit[0];
3208 TextMetrics const & tm = textMetrics(sl.text());
3209 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
3211 LBUFERR(!pm.rows().empty());
3212 y -= pm.rows()[0].ascent();
3214 // FIXME: document this mess
3216 if (sl.pos() > 0 && dit.depth() == 1) {
3218 if (pos && dit.boundary())
3220 // lyxerr << "coordOffset: boundary:" << dit.boundary() << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
3221 rend = pm.pos2row(pos);
3223 rend = pm.pos2row(sl.pos());
3225 size_t rend = pm.pos2row(sl.pos());
3227 for (size_t rit = 0; rit != rend; ++rit)
3228 y += pm.rows()[rit].height();
3229 y += pm.rows()[rend].ascent();
3231 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
3233 // Make relative position from the nested inset now bufferview absolute.
3234 int xx = bottom_tm.cursorX(dit.bottom(), dit.boundary() && dit.depth() == 1);
3237 // In the RTL case place the nested inset at the left of the cursor in
3238 // the outer paragraph
3239 bool boundary_1 = dit.boundary() && 1 == dit.depth();
3240 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
3248 Point BufferView::getPos(DocIterator const & dit) const
3250 if (!paragraphVisible(dit))
3251 return Point(-1, -1);
3253 CursorSlice const & bot = dit.bottom();
3254 TextMetrics const & tm = textMetrics(bot.text());
3256 // offset from outer paragraph
3257 Point p = coordOffset(dit);
3258 p.y_ += tm.parMetrics(bot.pit()).position();
3263 bool BufferView::paragraphVisible(DocIterator const & dit) const
3265 CursorSlice const & bot = dit.bottom();
3266 TextMetrics const & tm = textMetrics(bot.text());
3268 return tm.contains(bot.pit());
3272 void BufferView::caretPosAndDim(Point & p, Dimension & dim) const
3274 Cursor const & cur = cursor();
3275 if (cur.inMathed()) {
3276 MathRow const & mrow = mathRow(&cur.cell());
3277 dim = mrow.caret_dim;
3279 Font const font = cur.real_current_font;
3280 frontend::FontMetrics const & fm = theFontMetrics(font);
3281 // lineWidth() can be 0 to mean 'thin line' on HiDpi, but the
3282 // caret drawing code is not prepared for that.
3283 dim.wid = max(fm.lineWidth(), 1);
3284 dim.asc = fm.maxAscent();
3285 dim.des = fm.maxDescent();
3287 if (lyxrc.cursor_width > 0)
3288 dim.wid = lyxrc.cursor_width;
3291 // center fat carets horizontally
3292 p.x_ -= dim.wid / 2;
3298 void BufferView::buildCaretGeometry(bool complet)
3302 caretPosAndDim(p, dim);
3304 Cursor const & cur = d->cursor_;
3305 Font const & realfont = cur.real_current_font;
3306 frontend::FontMetrics const & fm = theFontMetrics(realfont.fontInfo());
3307 bool const isrtl = realfont.isVisibleRightToLeft();
3308 int const dir = isrtl ? -1 : 1;
3310 frontend::CaretGeometry & cg = d->caret_geometry_;
3313 // The caret itself, slanted for italics in text edit mode except
3314 // for selections because the selection rect does not slant
3315 bool const slant = fm.italic() && cur.inTexted() && !cur.selection();
3316 double const slope = slant ? fm.italicSlope() : 0;
3317 cg.shapes.push_back(
3318 {{iround(p.x_ + dim.asc * slope), p.y_},
3319 {iround(p.x_ - dim.des * slope), p.y_ + dim.height()},
3320 {iround(p.x_ + dir * dim.wid - dim.des * slope), p.y_ + dim.height()},
3321 {iround(p.x_ + dir * dim.wid + dim.asc * slope), p.y_}}
3324 // The language indicator _| (if needed)
3325 Language const * doclang = buffer().params().language;
3326 if (!((realfont.language() == doclang && isrtl == doclang->rightToLeft())
3327 || realfont.language() == latex_language)) {
3328 int const lx = dim.height() / 3;
3329 int const xx = iround(p.x_ - dim.des * slope);
3330 int const yy = p.y_ + dim.height();
3331 cg.shapes.push_back(
3332 {{xx, yy - dim.wid},
3333 {xx + dir * (dim.wid + lx - 1), yy - dim.wid},
3334 {xx + dir * (dim.wid + lx - 1), yy},
3339 // The completion triangle |> (if needed)
3341 int const m = p.y_ + dim.height() / 2;
3342 int const d = dim.height() / 8;
3343 // offset for slanted carret
3344 int const sx = iround((dim.asc - (dim.height() / 2 - d)) * slope);
3345 // starting position x
3346 int const xx = p.x_ + dir * dim.wid + sx;
3347 cg.shapes.push_back(
3351 {xx, m + d - dim.wid},
3352 {xx + dir * d - dim.wid, m},
3353 {xx, m - d + dim.wid}}
3357 // compute extremal x values
3359 cg.right = -1000000;
3361 cg.bottom = -1000000;
3362 for (auto const & shape : cg.shapes)
3363 for (Point const & p : shape) {
3364 cg.left = min(cg.left, p.x_);
3365 cg.right = max(cg.right, p.x_);
3366 cg.top = min(cg.top, p.y_);
3367 cg.bottom = max(cg.bottom, p.y_);
3372 frontend::CaretGeometry const & BufferView::caretGeometry() const
3374 return d->caret_geometry_;
3378 bool BufferView::caretInView() const
3380 if (!paragraphVisible(cursor()))
3384 caretPosAndDim(p, dim);
3386 // does the cursor touch the screen ?
3387 if (p.y_ + dim.height() < 0 || p.y_ >= workHeight())
3393 int BufferView::horizScrollOffset() const
3395 return d->horiz_scroll_offset_;
3399 int BufferView::horizScrollOffset(Text const * text,
3400 pit_type pit, pos_type pos) const
3402 // Is this a row that is currently scrolled?
3403 if (!d->current_row_slice_.empty()
3404 && &text->inset() == d->current_row_slice_.inset().asInsetText()
3405 && pit == d->current_row_slice_.pit()
3406 && pos == d->current_row_slice_.pos())
3407 return d->horiz_scroll_offset_;
3412 void BufferView::setCurrentRowSlice(CursorSlice const & rowSlice)
3414 // nothing to do if the cursor was already on this row
3415 if (d->current_row_slice_ == rowSlice)
3418 // if the (previous) current row was scrolled, we have to
3419 // remember it in order to repaint it next time.
3420 if (d->horiz_scroll_offset_ != 0) {
3421 // search the old row in cache and mark it changed
3422 for (auto & tm_pair : d->text_metrics_) {
3423 if (&tm_pair.first->inset() == rowSlice.inset().asInsetText()) {
3424 tm_pair.second.setRowChanged(rowSlice.pit(), rowSlice.pos());
3425 // We found it, no need to continue.
3431 // Since we changed row, the scroll offset is not valid anymore
3432 d->horiz_scroll_offset_ = 0;
3433 d->current_row_slice_ = rowSlice;
3437 void BufferView::checkCursorScrollOffset()
3439 CursorSlice rowSlice = d->cursor_.bottom();
3440 TextMetrics const & tm = textMetrics(rowSlice.text());
3442 // Stop if metrics have not been computed yet, since it means
3443 // that there is nothing to do.
3444 if (!tm.contains(rowSlice.pit()))
3446 ParagraphMetrics const & pm = tm.parMetrics(rowSlice.pit());
3447 Row const & row = pm.getRow(rowSlice.pos(),
3448 d->cursor_.boundary() && rowSlice == d->cursor_.top());
3449 rowSlice.pos() = row.pos();
3451 // Set the row on which the cursor lives.
3452 setCurrentRowSlice(rowSlice);
3454 // Current x position of the cursor in pixels
3455 int cur_x = getPos(d->cursor_).x_;
3457 // Horizontal scroll offset of the cursor row in pixels
3458 int offset = d->horiz_scroll_offset_;
3459 int const MARGIN = 2 * theFontMetrics(d->cursor_.real_current_font).em()
3461 if (row.right_x() <= workWidth() - row.right_margin) {
3462 // Row is narrower than the work area, no offset needed.
3465 if (cur_x - offset < MARGIN) {
3466 // cursor would be too far right
3467 offset = cur_x - MARGIN;
3468 } else if (cur_x - offset > workWidth() - MARGIN) {
3469 // cursor would be too far left
3470 offset = cur_x - workWidth() + MARGIN;
3472 // Correct the offset to make sure that we do not scroll too much
3475 if (row.right_x() - offset < workWidth() - row.right_margin)
3476 offset = row.right_x() - workWidth() + row.right_margin;
3479 //lyxerr << "cur_x=" << cur_x << ", offset=" << offset << ", row.wid=" << row.width() << ", margin=" << MARGIN << endl;
3481 if (offset != d->horiz_scroll_offset_) {
3482 LYXERR(Debug::PAINTING, "Horiz. scroll offset changed from "
3483 << d->horiz_scroll_offset_ << " to " << offset);
3485 if (d->update_strategy_ == NoScreenUpdate)
3486 d->update_strategy_ = SingleParUpdate;
3489 d->horiz_scroll_offset_ = offset;
3493 void BufferView::draw(frontend::Painter & pain, bool paint_caret)
3495 if (height_ == 0 || width_ == 0)
3497 LYXERR(Debug::PAINTING, (pain.isNull() ? "\t\t--- START NODRAW ---"
3498 : "\t\t*** START DRAWING ***"));
3499 Text & text = buffer_.text();
3500 TextMetrics const & tm = d->text_metrics_[&text];
3501 int const y = tm.first().second->position();
3502 PainterInfo pi(this, pain);
3504 // Check whether the row where the cursor lives needs to be scrolled.
3505 // Update the drawing strategy if needed.
3506 checkCursorScrollOffset();
3508 switch (d->update_strategy_) {
3510 case NoScreenUpdate:
3511 // no screen painting is actually needed. In nodraw stage
3512 // however, the different coordinates of insets and paragraphs
3513 // needs to be updated.
3514 LYXERR(Debug::PAINTING, "Strategy: NoScreenUpdate");
3515 if (pain.isNull()) {
3516 pi.full_repaint = true;
3519 pi.full_repaint = false;
3524 case SingleParUpdate:
3525 pi.full_repaint = false;
3526 LYXERR(Debug::PAINTING, "Strategy: SingleParUpdate");
3527 // In general, only the current row of the outermost paragraph
3528 // will be redrawn. Particular cases where selection spans
3529 // multiple paragraph are correctly detected in TextMetrics.
3533 case DecorationUpdate:
3534 // FIXME: We should also distinguish DecorationUpdate to avoid text
3535 // drawing if possible. This is not possible to do easily right now
3536 // because of the single backing pixmap.
3538 case FullScreenUpdate:
3540 LYXERR(Debug::PAINTING,
3541 ((d->update_strategy_ == FullScreenUpdate)
3542 ? "Strategy: FullScreenUpdate"
3543 : "Strategy: DecorationUpdate"));
3545 // The whole screen, including insets, will be refreshed.
3546 pi.full_repaint = true;
3548 // Clear background.
3549 pain.fillRectangle(0, 0, width_, height_,
3550 pi.backgroundColor(&buffer_.inset()));
3555 // and possibly grey out below
3556 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3557 int const y2 = lastpm.second->position() + lastpm.second->descent();
3560 Color color = buffer().isInternal()
3561 ? Color_background : Color_bottomarea;
3562 pain.fillRectangle(0, y2, width_, height_ - y2, color);
3566 LYXERR(Debug::PAINTING, (pain.isNull() ? "\t\t --- END NODRAW ---"
3567 : "\t\t *** END DRAWING ***"));
3569 // The scrollbar needs an update.
3570 // FIXME: does it always? see ticket #11947.
3571 updateScrollbarParameters();
3573 // Normalize anchor for next time
3574 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
3575 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3576 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
3577 ParagraphMetrics const & pm = tm.parMetrics(pit);
3578 if (pm.position() + pm.descent() > 0) {
3579 if (d->anchor_pit_ != pit
3580 || d->anchor_ypos_ != pm.position())
3581 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
3582 << " anchor ypos = " << d->anchor_ypos_);
3583 d->anchor_pit_ = pit;
3584 d->anchor_ypos_ = pm.position();
3588 if (!pain.isNull()) {
3589 // reset the update flags, everything has been done
3590 d->update_flags_ = Update::None;
3593 // If a caret has to be painted, mark its text row as dirty to
3594 //make sure that it will be repainted on next redraw.
3595 /* FIXME: investigate whether this can be avoided when the cursor did not
3599 Cursor cur(d->cursor_);
3600 while (cur.depth() > 1) {
3601 if (!cur.inTexted())
3603 TextMetrics const & tm = textMetrics(cur.text());
3604 if (d->caret_geometry_.left >= tm.origin().x_
3605 && d->caret_geometry_.right <= tm.origin().x_ + tm.dim().width())
3609 cur.textRow().changed(true);
3614 void BufferView::message(docstring const & msg)
3617 d->gui_->message(msg);
3621 void BufferView::showDialog(string const & name)
3624 d->gui_->showDialog(name, string());
3628 void BufferView::showDialog(string const & name,
3629 string const & data, Inset * inset)
3632 d->gui_->showDialog(name, data, inset);
3636 void BufferView::updateDialog(string const & name, string const & data)
3639 d->gui_->updateDialog(name, data);
3643 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
3649 // FIXME: Move this out of BufferView again
3650 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
3652 if (!fname.isReadableFile()) {
3653 docstring const error = from_ascii(strerror(errno));
3654 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3655 docstring const text =
3656 bformat(_("Could not read the specified document\n"
3657 "%1$s\ndue to the error: %2$s"), file, error);
3658 Alert::error(_("Could not read file"), text);
3662 if (!fname.isReadableFile()) {
3663 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3664 docstring const text =
3665 bformat(_("%1$s\n is not readable."), file);
3666 Alert::error(_("Could not open file"), text);
3670 // FIXME UNICODE: We don't know the encoding of the file
3671 docstring file_content = fname.fileContents("UTF-8");
3672 if (file_content.empty()) {
3673 Alert::error(_("Reading not UTF-8 encoded file"),
3674 _("The file is not UTF-8 encoded.\n"
3675 "It will be read as local 8Bit-encoded.\n"
3676 "If this does not give the correct result\n"
3677 "then please change the encoding of the file\n"
3678 "to UTF-8 with a program other than LyX.\n"));
3679 file_content = fname.fileContents("local8bit");
3682 return normalize_c(file_content);
3686 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
3688 docstring const tmpstr = contentsOfPlaintextFile(f);
3693 Cursor & cur = cursor();
3694 cap::replaceSelection(cur);
3695 buffer_.undo().recordUndo(cur);
3697 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
3699 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
3701 buffer_.changed(true);
3705 docstring const & BufferView::inlineCompletion() const
3707 return d->inlineCompletion_;
3711 size_t BufferView::inlineCompletionUniqueChars() const
3713 return d->inlineCompletionUniqueChars_;
3717 DocIterator const & BufferView::inlineCompletionPos() const
3719 return d->inlineCompletionPos_;
3723 void BufferView::resetInlineCompletionPos()
3725 d->inlineCompletionPos_ = DocIterator();
3729 bool samePar(DocIterator const & a, DocIterator const & b)
3731 if (a.empty() && b.empty())
3733 if (a.empty() || b.empty())
3735 if (a.depth() != b.depth())
3737 return &a.innerParagraph() == &b.innerParagraph();
3741 void BufferView::setInlineCompletion(Cursor const & cur, DocIterator const & pos,
3742 docstring const & completion, size_t uniqueChars)
3744 uniqueChars = min(completion.size(), uniqueChars);
3745 bool changed = d->inlineCompletion_ != completion
3746 || d->inlineCompletionUniqueChars_ != uniqueChars;
3747 bool singlePar = true;
3748 d->inlineCompletion_ = completion;
3749 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
3751 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
3754 DocIterator const & old = d->inlineCompletionPos_;
3756 //lyxerr << "inlineCompletionPos changed" << std::endl;
3757 // old or pos are in another paragraph?
3758 if ((!samePar(cur, pos) && !pos.empty())
3759 || (!samePar(cur, old) && !old.empty())) {
3761 //lyxerr << "different paragraph" << std::endl;
3763 d->inlineCompletionPos_ = pos;
3768 if (singlePar && !(cur.result().screenUpdate() & Update::Force))
3769 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
3771 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::Force);
3776 bool BufferView::clickableInset() const
3778 return d->clickable_inset_;