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 "BiblioInfo.h"
24 #include "CoordCache.h"
26 #include "CutAndPaste.h"
27 #include "DispatchResult.h"
28 #include "ErrorList.h"
29 #include "FuncRequest.h"
30 #include "FuncStatus.h"
33 #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/docstring_list.h"
73 #include "support/filetools.h"
74 #include "support/gettext.h"
75 #include "support/lassert.h"
76 #include "support/Length.h"
77 #include "support/Lexer.h"
78 #include "support/lstrings.h"
79 #include "support/lyxlib.h"
80 #include "support/types.h"
92 using namespace lyx::support;
96 namespace Alert = frontend::Alert;
100 /// Return an inset of this class if it exists at the current cursor position
102 T * getInsetByCode(Cursor const & cur, InsetCode code)
104 DocIterator it = cur;
105 Inset * inset = it.nextInset();
106 if (inset && inset->lyxCode() == code)
107 return static_cast<T*>(inset);
112 /// Note that comparing contents can only be used for InsetCommand
113 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
114 docstring const & contents)
116 DocIterator tmpdit = dit;
119 Inset const * inset = tmpdit.nextInset();
121 bool const valid_code = std::find(codes.begin(), codes.end(),
122 inset->lyxCode()) != codes.end();
123 InsetCommand const * ic = inset->asInsetCommand();
124 bool const same_or_no_contents = contents.empty()
125 || (ic && (ic->getFirstNonOptParam() == contents));
127 if (valid_code && same_or_no_contents) {
132 tmpdit.forwardInset();
139 /// Looks for next inset with one of the given codes.
140 /// Note that same_content can only be used for InsetCommand
141 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
145 DocIterator tmpdit = dit;
146 tmpdit.forwardInset();
150 Inset const * inset = tmpdit.nextInset();
151 if (same_content && inset) {
152 InsetCommand const * ic = inset->asInsetCommand();
154 bool const valid_code = std::find(codes.begin(), codes.end(),
155 ic->lyxCode()) != codes.end();
157 contents = ic->getFirstNonOptParam();
161 if (!findNextInset(tmpdit, codes, contents)) {
162 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
163 inset = &tmpdit.bottom().inset();
164 tmpdit = doc_iterator_begin(&inset->buffer(), inset);
165 if (!findNextInset(tmpdit, codes, contents))
177 /// Moves cursor to the next inset with one of the given codes.
178 bool gotoInset(BufferView * bv, vector<InsetCode> const & codes,
181 Cursor tmpcur = bv->cursor();
182 if (!findInset(tmpcur, codes, same_content)) {
183 bv->cursor().message(_("No more insets"));
187 tmpcur.clearSelection();
188 bv->setCursor(tmpcur);
189 return bv->scrollToCursor(bv->cursor(), SCROLL_TOP);
193 /// A map from a Text to the associated text metrics
194 typedef map<Text const *, TextMetrics> TextMetricsCache;
196 enum ScreenUpdateStrategy {
206 /////////////////////////////////////////////////////////////////////
210 /////////////////////////////////////////////////////////////////////
212 struct BufferView::Private
214 Private(BufferView & bv) :
215 update_strategy_(FullScreenUpdate),
216 update_flags_(Update::Force),
217 cursor_(bv), anchor_pit_(0), anchor_ypos_(10000),
218 wh_(0), inlineCompletionUniqueChars_(0),
219 last_inset_(nullptr), mouse_position_cache_(),
220 gui_(nullptr), bookmark_edit_position_(-1),
221 horiz_scroll_offset_(0), clickable_inset_(false)
223 xsel_cache_.set = false;
227 ScrollbarParameters scrollbarParameters_;
229 ScreenUpdateStrategy update_strategy_;
231 Update::flags update_flags_;
233 CoordCache coord_cache_;
235 typedef unordered_map<MathData const *, MathRow> MathRows;
238 /// this is used to handle XSelection events in the right manner.
247 pit_type anchor_pit_;
250 /// Estimated average par height for scrollbar.
253 vector<int> par_height_;
256 DocIterator inlineCompletionPos_;
258 docstring inlineCompletion_;
260 size_t inlineCompletionUniqueChars_;
262 /// keyboard mapping object.
265 /// last visited inset.
266 /** kept to send setMouseHover(false).
267 * Not owned, so don't delete.
269 Inset const * last_inset_;
271 /// position of the mouse at the time of the last mouse move
272 /// This is used to update the hovering status of inset in
273 /// cases where the buffer is scrolled, but the mouse didn't move.
274 Point mouse_position_cache_;
276 mutable TextMetricsCache text_metrics_;
279 /** Not owned, so don't delete.
281 frontend::GuiBufferViewDelegate * gui_;
284 map<string, Inset *> edited_insets_;
286 // cache for id of the paragraph which was edited the last time
287 int bookmark_edit_position_;
289 /// When the row where the cursor lies is scrolled, this
290 /// contains the scroll offset
291 int horiz_scroll_offset_;
292 /// a slice pointing to the start of the row where the cursor
293 /// is (at last draw time)
294 CursorSlice current_row_slice_;
295 /// are we hovering something that we can click
296 bool clickable_inset_;
297 /// shape of the caret
298 frontend::CaretGeometry caret_geometry_;
300 bool mouse_selecting_ = false;
301 /// Reference value for statistics (essentially subtract this from the actual value to see relative counts)
302 /// (words/chars/chars no blanks)
303 int stats_ref_value_w_ = 0;
304 int stats_ref_value_c_ = 0;
305 int stats_ref_value_nb_ = 0;
306 bool stats_update_trigger_ = false;
311 BufferView::BufferView(Buffer & buf)
312 : width_(0), height_(0), full_screen_(false), buffer_(buf),
313 d(new Private(*this))
315 d->xsel_cache_.set = false;
316 d->intl_.initKeyMapper(lyxrc.use_kbmap);
318 d->cursor_.setBuffer(&buf);
319 d->cursor_.push(buffer_.inset());
320 d->cursor_.resetAnchor();
321 d->cursor_.setCurrentFont();
323 buffer_.updatePreviews();
327 BufferView::~BufferView()
329 // current buffer is going to be switched-off, save cursor pos
330 // Ideally, the whole cursor stack should be saved, but session
331 // currently can only handle bottom (whole document) level pit and pos.
332 // That is to say, if a cursor is in a nested inset, it will be
333 // restore to the left of the top level inset.
334 LastFilePosSection::FilePos fp;
335 fp.file = buffer_.fileName();
336 fp.pit = d->cursor_.bottom().pit();
337 fp.pos = d->cursor_.bottom().pos();
338 theSession().lastFilePos().save(fp);
341 d->last_inset_->setMouseHover(this, false);
347 void BufferView::copySettingsFrom(BufferView const & bv)
349 setCursor(bv.cursor());
350 d->anchor_pit_ = bv.d->anchor_pit_;
351 d->anchor_ypos_ = bv.d->anchor_ypos_;
355 int BufferView::defaultMargin() const
357 // The value used to be hardcoded to 10
358 return zoomedPixels(20);
362 int BufferView::rightMargin() const
364 const int screen_width = inPixels(lyxrc.screen_width);
366 // The additional test for the case the outliner is opened.
367 if (!lyxrc.screen_limit || width_ < screen_width + 2 * defaultMargin()) {
368 return defaultMargin();
370 return (width_ - screen_width) / 2;
375 int BufferView::leftMargin() const
377 return rightMargin();
381 int BufferView::topMargin() const
383 // Original value was 20px at 100dpi. For internal buffers like in
384 // advanced search and replace, a value of 5px is enough.
385 return zoomedPixels(buffer().isInternal() ? 5 : 20);
389 int BufferView::bottomMargin() const
395 int BufferView::inPixels(Length const & len) const
397 Font const font = buffer().params().getFont();
398 return len.inPixels(workWidth(), theFontMetrics(font).em());
402 int BufferView::zoomedPixels(int pix) const
404 // FIXME: the dpi setting should really depend on the BufferView
405 // (think different monitors).
407 // Zoom factor specified by user in percent
408 double const zoom = lyxrc.currentZoom / 100.0; // [percent]
410 // DPI setting for monitor relative to 100dpi
411 double const dpizoom = lyxrc.dpi / 100.0; // [per 100dpi]
413 return support::iround(pix * zoom * dpizoom);
417 bool BufferView::isTopScreen() const
419 return 0 == d->scrollbarParameters_.min;
423 bool BufferView::isBottomScreen() const
425 return 0 == d->scrollbarParameters_.max;
429 Intl & BufferView::getIntl()
435 Intl const & BufferView::getIntl() const
441 CoordCache & BufferView::coordCache()
443 return d->coord_cache_;
447 CoordCache const & BufferView::coordCache() const
449 return d->coord_cache_;
453 bool BufferView::hasMathRow(MathData const * cell) const
455 return d->math_rows_.find(cell) != d->math_rows_.end();
459 MathRow const & BufferView::mathRow(MathData const * cell) const
461 auto it = d->math_rows_.find(cell);
462 LATTEST(it != d->math_rows_.end());
467 void BufferView::setMathRow(MathData const * cell, MathRow const & mrow)
469 d->math_rows_[cell] = mrow;
473 Buffer & BufferView::buffer()
479 Buffer const & BufferView::buffer() const
485 docstring const & BufferView::searchRequestCache() const
487 return theClipboard().getFindBuffer();
491 void BufferView::setSearchRequestCache(docstring const & text)
499 docstring const search = string2find(text, casesensitive, matchword,
500 forward, wrap, instant, onlysel);
501 theClipboard().setFindBuffer(search);
505 bool BufferView::needsFitCursor() const
507 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
508 frontend::FontMetrics const & fm =
509 theFontMetrics(d->cursor_.getFont().fontInfo());
510 int const asc = fm.maxAscent();
511 int const des = fm.maxDescent();
512 Point const p = getPos(d->cursor_);
513 if (p.y_ - asc >= 0 && p.y_ + des < height_)
522 // this is for debugging only.
523 string flagsAsString(Update::flags flags)
525 if (flags == Update::None)
527 return string((flags & Update::FitCursor) ? "FitCursor " : "")
528 + ((flags & Update::Force) ? "Force " : "")
529 + ((flags & Update::ForceDraw) ? "ForceDraw " : "")
530 + ((flags & Update::SinglePar) ? "SinglePar " : "")
531 + ((flags & Update::Decoration) ? "Decoration " : "");
536 void BufferView::processUpdateFlags(Update::flags flags)
538 LYXERR(Debug::PAINTING, "BufferView::processUpdateFlags( "
539 << flagsAsString(flags) << ") buffer: " << &buffer_);
541 // Case when no explicit update is requested.
542 if (flags == Update::None || !ready())
545 /* FIXME We would like to avoid doing this here, since it is very
546 * expensive and is called in updateBuffer already. However, even
547 * inserting a plain character can invalidate the overly fragile
548 * tables of child documents built by updateMacros. Some work is
549 * needed to avoid doing that when not necessary.
551 buffer_.updateMacros();
553 // First check whether the metrics and inset positions should be updated
554 if (flags & Update::Force) {
555 // This will compute all metrics and positions.
557 // metrics is done, full drawing is necessary now
558 flags = (flags & ~Update::Force) | Update::ForceDraw;
560 /* If a single paragraph update has been requested and we are not
561 * already repainting all, check whether this update changes the
562 * paragraph metrics. If it does, then compute all metrics (in
563 * case the paragraph is in an inset)
565 * We handle this before FitCursor because the later will require
566 * correct metrics at cursor position.
568 else if ((flags & Update::SinglePar) && !(flags & Update::ForceDraw)) {
569 if (!singleParUpdate())
572 else if (flags & Update::ForceDraw)
573 // This will compute only the needed metrics and update positions.
574 updateMetrics(false);
576 // Then make sure that the screen contains the cursor if needed
577 if (flags & Update::FitCursor) {
578 if (needsFitCursor()) {
579 // First try to make the selection start visible
580 // (which is just the cursor when there is no selection)
581 scrollToCursor(d->cursor_.selectionBegin(), SCROLL_VISIBLE);
582 // Metrics have to be updated
583 updateMetrics(false);
584 // Is the cursor visible? (only useful if cursor is at end of selection)
585 if (needsFitCursor()) {
586 // then try to make cursor visible instead
587 scrollToCursor(d->cursor_, SCROLL_VISIBLE);
588 // Metrics have to be recomputed (maybe again)
589 updateMetrics(false);
592 flags = (flags & ~Update::FitCursor) | Update::ForceDraw;
595 if (lyxrc.draw_strategy == LyXRC::DS_FULL)
596 flags = flags | Update::ForceDraw;
598 // Add flags to the the update flags. These will be reset to None
599 // after the redraw is actually done
600 d->update_flags_ = d->update_flags_ | flags;
601 LYXERR(Debug::PAINTING, "Cumulative flags: " << flagsAsString(flags));
603 // Now compute the update strategy
604 // Possibly values in flag are None, SinglePar, Decoration, ForceDraw
605 LATTEST((d->update_flags_ & ~(Update::None | Update::SinglePar
606 | Update::Decoration | Update::ForceDraw)) == 0);
608 if (d->update_flags_ & Update::ForceDraw)
609 d->update_strategy_ = FullScreenUpdate;
610 else if (d->update_flags_ & Update::Decoration)
611 d->update_strategy_ = DecorationUpdate;
612 else if (d->update_flags_ & Update::SinglePar)
613 d->update_strategy_ = SingleParUpdate;
615 // no need to redraw anything.
616 d->update_strategy_ = NoScreenUpdate;
619 updateHoveredInset();
622 buffer_.changed(false);
626 void BufferView::updateScrollbarParameters()
631 // We prefer fixed size line scrolling.
632 d->scrollbarParameters_.single_step = defaultRowHeight();
633 // We prefer full screen page scrolling.
634 d->scrollbarParameters_.page_step = height_;
636 Text & t = buffer_.text();
637 TextMetrics & tm = d->text_metrics_[&t];
639 LYXERR(Debug::SCROLLING, " Updating scrollbar: height: "
640 << t.paragraphs().size()
641 << " curr par: " << d->cursor_.bottom().pit()
642 << " default height " << defaultRowHeight());
644 size_t const parsize = t.paragraphs().size();
645 if (d->par_height_.size() != parsize) {
646 d->par_height_.clear();
647 // FIXME: We assume a default paragraph height of 2 rows. This
648 // should probably be pondered with the screen width.
649 d->par_height_.resize(parsize, defaultRowHeight() * 2);
652 // Look at paragraph heights on-screen
653 pair<pit_type, ParagraphMetrics const *> first = tm.first();
654 pair<pit_type, ParagraphMetrics const *> last = tm.last();
655 for (pit_type pit = first.first; pit <= last.first; ++pit) {
656 d->par_height_[pit] = tm.parMetrics(pit).height();
657 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
658 << d->par_height_[pit]);
661 int top_pos = first.second->top();
662 int bottom_pos = last.second->bottom();
663 bool first_visible = first.first == 0 && top_pos >= 0;
664 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
665 if (first_visible && last_visible) {
666 d->scrollbarParameters_.min = 0;
667 d->scrollbarParameters_.max = 0;
671 d->scrollbarParameters_.min = top_pos;
672 for (size_t i = 0; i != size_t(first.first); ++i)
673 d->scrollbarParameters_.min -= d->par_height_[i];
674 d->scrollbarParameters_.max = bottom_pos;
675 for (size_t i = last.first + 1; i != parsize; ++i)
676 d->scrollbarParameters_.max += d->par_height_[i];
678 // The reference is the top position so we remove one page.
679 if (lyxrc.scroll_below_document)
680 d->scrollbarParameters_.max -= minVisiblePart();
682 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
684 // 0 must be inside the range as it denotes the current position
685 if (d->scrollbarParameters_.max < 0)
686 d->scrollbarParameters_.max = 0;
687 if (d->scrollbarParameters_.min > 0)
688 d->scrollbarParameters_.min = 0;
692 ScrollbarParameters const & BufferView::scrollbarParameters() const
694 return d->scrollbarParameters_;
698 docstring BufferView::toolTip(int x, int y) const
700 // Get inset under mouse, if there is one.
701 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
703 // No inset, no tooltip...
705 return covering_inset->toolTip(*this, x, y);
709 string BufferView::contextMenu(int x, int y) const
711 //If there is a selection, return the containing inset menu
712 if (d->cursor_.selection())
713 return d->cursor_.inset().contextMenu(*this, x, y);
715 // Get inset under mouse, if there is one.
716 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
717 if (covering_inset) {
718 if (covering_inset->asInsetMath()) {
719 CoordCache::Insets const & inset_cache =
720 coordCache().getInsets();
721 Inset const * inner_inset = mathContextMenu(
722 covering_inset->asInsetMath()->asNestInset(),
725 return inner_inset->contextMenu(*this, x, y);
727 return covering_inset->contextMenu(*this, x, y);
730 return buffer_.inset().contextMenu(*this, x, y);
734 Inset const * BufferView::mathContextMenu(InsetMathNest const * inset,
735 CoordCache::Insets const & inset_cache, int x, int y) const
737 for (size_t i = 0; i < inset->nargs(); ++i) {
738 MathData const & ar = inset->cell(i);
739 for (size_t j = 0; j < ar.size(); ++j) {
740 string const name = lyxerr.debugging(Debug::MATHED)
741 ? insetName(ar[j].nucleus()->lyxCode())
743 LYXERR(Debug::MATHED, "Examining inset: " << name);
744 if (!ar[j].nucleus()->contextMenuName().empty()) {
745 if (inset_cache.covers(ar[j].nucleus(), x, y)) {
746 LYXERR(Debug::MATHED, "Hit inset: "
748 return ar[j].nucleus();
751 InsetMathNest const * imn =
752 ar[j].nucleus()->asNestInset();
754 Inset const * inner =
755 mathContextMenu(imn, inset_cache, x, y);
765 void BufferView::scrollDocView(int const pixels, bool update)
767 // The scrollbar values are relative to the top of the screen, therefore the
768 // offset is equal to the target value.
770 // No scrolling at all? No need to redraw anything
774 // If part of the existing paragraphs will remain visible, prefer to
776 TextMetrics const & tm = textMetrics(&buffer_.text());
777 if (tm.first().second->top() - pixels <= height_
778 && tm.last().second->bottom() - pixels >= 0) {
779 LYXERR(Debug::SCROLLING, "small skip");
780 d->anchor_ypos_ -= pixels;
781 processUpdateFlags(Update::ForceDraw);
785 // cut off at the top
786 if (pixels <= d->scrollbarParameters_.min) {
787 DocIterator dit = doc_iterator_begin(&buffer_);
788 showCursor(dit, SCROLL_VISIBLE, update);
789 LYXERR(Debug::SCROLLING, "scroll to top");
793 // cut off at the bottom
794 if (pixels >= d->scrollbarParameters_.max) {
795 DocIterator dit = doc_iterator_end(&buffer_);
797 showCursor(dit, SCROLL_VISIBLE, update);
798 LYXERR(Debug::SCROLLING, "scroll to bottom");
802 LYXERR(Debug::SCROLLING, "search paragraph");
803 // find paragraph at target position
804 int par_pos = d->scrollbarParameters_.min;
806 for (; i != int(d->par_height_.size()); ++i) {
807 par_pos += d->par_height_[i];
808 if (par_pos >= pixels)
812 if (par_pos < pixels) {
813 // It seems we didn't find the correct pit so stay on the safe side and
815 LYXERR0("scrolling position not found!");
816 scrollDocView(d->scrollbarParameters_.max, update);
820 DocIterator dit = doc_iterator_begin(&buffer_);
822 LYXERR(Debug::SCROLLING, "pixels = " << pixels << " -> scroll to pit " << i);
823 showCursor(dit, SCROLL_VISIBLE, update);
827 // FIXME: this method is not working well.
828 void BufferView::setCursorFromScrollbar()
830 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
832 int const height = 2 * defaultRowHeight();
833 int const first = height;
834 int const last = height_ - height;
836 Cursor const & oldcur = d->cursor_;
838 switch (cursorStatus(oldcur)) {
846 int const y = getPos(oldcur).y_;
847 newy = min(last, max(y, first));
851 // We reset the cursor because cursorStatus() does not
852 // work when the cursor is within mathed.
855 tm.setCursorFromCoordinates(cur, 0, newy);
857 // update the bufferview cursor and notify insets
858 // FIXME: Care about the d->cursor_ flags to redraw if needed
859 Cursor old = d->cursor_;
861 // the DEPM call in mouseSetCursor() might have destroyed the
862 // paragraph the cursor is in.
863 bool badcursor = old.fixIfBroken();
864 badcursor |= notifyCursorLeavesOrEnters(old, d->cursor_);
866 d->cursor_.fixIfBroken();
870 Change const BufferView::getCurrentChange() const
872 if (!d->cursor_.selection())
873 return Change(Change::UNCHANGED);
875 DocIterator dit = d->cursor_.selectionBegin();
876 // The selected content might have been changed (see #7685)
877 dit = dit.getInnerText();
878 return dit.paragraph().lookupChange(dit.pos());
882 // this could be used elsewhere as well?
883 // FIXME: This does not work within mathed!
884 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
886 Point const p = getPos(dit);
889 if (p.y_ > workHeight())
895 void BufferView::bookmarkEditPosition()
897 // Don't eat cpu time for each keystroke
898 if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
901 d->bookmark_edit_position_ = d->cursor_.paragraph().id();
905 void BufferView::saveBookmark(unsigned int idx)
907 if (buffer().isInternal())
910 // tentatively save bookmark, id and pos will be used to
911 // acturately locate a bookmark in a 'live' lyx session.
912 // pit and pos will be updated with bottom level pit/pos
914 theSession().bookmarks().save(
916 d->cursor_.bottom().pit(),
917 d->cursor_.bottom().pos(),
918 d->cursor_.paragraph().id(),
923 // emit message signal.
924 message(_("Save bookmark"));
928 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
929 int top_id, pos_type top_pos)
931 bool success = false;
934 d->cursor_.clearSelection();
936 // if a valid par_id is given, try it first
937 // This is the case for a 'live' bookmark when unique paragraph ID
938 // is used to track bookmarks.
940 dit = buffer_.getParFromID(top_id);
942 dit.pos() = min(dit.paragraph().size(), top_pos);
943 // Some slices of the iterator may not be
944 // reachable (e.g. closed collapsible inset)
945 // so the dociterator may need to be
946 // shortened. Otherwise, setCursor may crash
947 // lyx when the cursor can not be set to these
949 size_t const n = dit.depth();
950 for (size_t i = 0; i < n; ++i)
951 if (!dit[i].inset().editable()) {
959 // if top_id == 0, or searching through top_id failed
960 // This is the case for a 'restored' bookmark when only bottom
961 // (document level) pit was saved. Because of this, bookmark
962 // restoration is inaccurate. If a bookmark was within an inset,
963 // it will be restored to the left of the outmost inset that contains
965 if (!success && bottom_pit < int(buffer_.paragraphs().size())) {
966 dit = doc_iterator_begin(&buffer_);
968 dit.pit() = bottom_pit;
969 dit.pos() = min(bottom_pos, dit.paragraph().size());
974 // Note: only bottom (document) level pit is set.
976 // set the current font.
977 d->cursor_.setCurrentFont();
978 // Do not forget to reset the anchor (see #9912)
979 d->cursor_.resetAnchor();
980 processUpdateFlags(Update::Force | Update::FitCursor);
987 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
989 if (d->cursor_.real_current_font.isRightToLeft()) {
990 if (d->intl_.keymap == Intl::PRIMARY)
991 d->intl_.keyMapSec();
993 if (d->intl_.keymap == Intl::SECONDARY)
994 d->intl_.keyMapPrim();
997 d->intl_.getTransManager().translateAndInsert(c, t, cur);
1001 int BufferView::workWidth() const
1007 void BufferView::recenter()
1009 showCursor(d->cursor_, SCROLL_CENTER, true);
1013 void BufferView::showCursor()
1015 showCursor(d->cursor_, SCROLL_VISIBLE, true);
1019 void BufferView::showCursor(DocIterator const & dit, ScrollType how,
1022 if (scrollToCursor(dit, how) && update)
1023 processUpdateFlags(Update::ForceDraw);
1027 bool BufferView::scrollToCursor(DocIterator const & dit, ScrollType how)
1029 // We are not properly started yet, delay until resizing is done.
1033 if (how == SCROLL_CENTER)
1034 LYXERR(Debug::SCROLLING, "Centering cursor in workarea");
1035 else if (how == SCROLL_TOP)
1036 LYXERR(Debug::SCROLLING, "Setting cursor to top of workarea");
1038 LYXERR(Debug::SCROLLING, "Making sure cursor is visible in workarea");
1040 CursorSlice const & bot = dit.bottom();
1041 TextMetrics & tm = textMetrics(bot.text());
1043 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
1044 pos_type bot_pit = bot.pit();
1045 if (bot_pit > max_pit) {
1046 // FIXME: Why does this happen?
1047 LYXERR0("bottom pit is greater that max pit: "
1048 << bot_pit << " > " << max_pit);
1052 if (bot_pit == tm.first().first - 1)
1053 tm.newParMetricsUp();
1054 else if (bot_pit == tm.last().first + 1)
1055 tm.newParMetricsDown();
1057 if (tm.contains(bot_pit) && how == SCROLL_VISIBLE) {
1058 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
1059 LBUFERR(!pm.rows().empty());
1060 // FIXME: smooth scrolling doesn't work in mathed.
1061 CursorSlice const & cs = dit.innerTextSlice();
1062 int const ypos = pm.position() + coordOffset(dit).y_;
1063 ParagraphMetrics const & inner_pm =
1064 textMetrics(cs.text()).parMetrics(cs.pit());
1065 Dimension const & row_dim =
1066 inner_pm.getRow(cs.pos(), dit.boundary()).dim();
1069 // We try to visualize the whole row, if the row height is larger than
1070 // the screen height, we scroll to a heuristic value of height_ / 4.
1071 // FIXME: This heuristic value should be replaced by a recursive search
1072 // for a row in the inset that can be visualized completely.
1073 if (row_dim.height() > height_) {
1074 if (ypos < defaultRowHeight())
1075 scrolled = scroll(ypos - height_ / 4);
1076 else if (ypos > height_ - defaultRowHeight())
1077 scrolled = scroll(ypos - 3 * height_ / 4);
1080 // If the top part of the row falls of the screen, we scroll
1081 // up to align the top of the row with the top of the screen.
1082 else if (ypos - row_dim.ascent() < 0 && ypos < height_) {
1083 int const ynew = row_dim.ascent();
1084 scrolled = scrollUp(ynew - ypos);
1087 // If the bottom of the row falls of the screen, we scroll down.
1088 else if (ypos + row_dim.descent() > height_ && ypos > 0) {
1089 int const ynew = height_ - row_dim.descent();
1090 scrolled = scrollDown(ypos - ynew);
1093 // else, nothing to do, the cursor is already visible so we just return.
1094 return scrolled != 0;
1097 // fix inline completion position
1098 if (d->inlineCompletionPos_.fixIfBroken())
1099 d->inlineCompletionPos_ = DocIterator();
1101 tm.redoParagraph(bot_pit);
1102 int const offset = coordOffset(dit).y_;
1103 pit_type const old_pit = d->anchor_pit_;
1104 d->anchor_pit_ = bot_pit;
1106 CursorSlice const & cs = dit.innerTextSlice();
1107 ParagraphMetrics const & inner_pm =
1108 textMetrics(cs.text()).parMetrics(cs.pit());
1109 Dimension const & row_dim =
1110 inner_pm.getRow(cs.pos(), dit.boundary()).dim();
1112 int const old_ypos = d->anchor_ypos_;
1113 d->anchor_ypos_ = - offset + row_dim.ascent();
1114 if (how == SCROLL_CENTER)
1115 d->anchor_ypos_ += height_/2 - row_dim.height() / 2;
1116 else if (offset > height_)
1117 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
1119 d->anchor_ypos_ = defaultRowHeight() * 2;
1121 return d->anchor_ypos_ != old_ypos || d->anchor_pit_ != old_pit;
1125 void BufferView::makeDocumentClass()
1127 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
1128 buffer_.params().makeDocumentClass(buffer_.isClone(), buffer_.isInternal());
1129 updateDocumentClass(olddc);
1133 void BufferView::updateDocumentClass(DocumentClassConstPtr olddc)
1135 StableDocIterator backcur(d->cursor_);
1136 ErrorList & el = buffer_.errorList("Class Switch");
1137 cap::switchBetweenClasses(
1138 olddc, buffer_.params().documentClassPtr(),
1139 static_cast<InsetText &>(buffer_.inset()), el);
1141 setCursor(backcur.asDocIterator(&buffer_));
1143 buffer_.errors("Class Switch");
1147 /** Return the change status at cursor position, taking into account the
1148 * status at each level of the document iterator (a table in a deleted
1149 * footnote is deleted).
1150 * When \param outer is true, the top slice is not looked at.
1152 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
1154 size_t const depth = dit.depth() - (outer ? 1 : 0);
1156 for (size_t i = 0 ; i < depth ; ++i) {
1157 CursorSlice const & slice = dit[i];
1158 if (!slice.inset().inMathed()
1159 && slice.pos() < slice.paragraph().size()) {
1160 Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
1161 if (ch != Change::UNCHANGED)
1165 return Change::UNCHANGED;
1169 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1171 FuncCode const act = cmd.action();
1173 // Can we use a readonly buffer?
1174 if (buffer_.isReadonly()
1175 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1176 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1177 if (buffer_.hasReadonlyFlag())
1178 flag.message(from_utf8(N_("Document is read-only")));
1180 flag.message(from_utf8(N_("Document has been modified externally")));
1181 flag.setEnabled(false);
1185 // Are we in a DELETED change-tracking region?
1186 if (lookupChangeType(d->cursor_, true) == Change::DELETED
1187 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1188 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1189 flag.message(from_utf8(N_("This portion of the document is deleted.")));
1190 flag.setEnabled(false);
1194 Cursor & cur = d->cursor_;
1196 if (cur.getStatus(cmd, flag))
1201 // FIXME: This is a bit problematic because we don't check if this is
1202 // a document BufferView or not for these LFUNs. We probably have to
1203 // dispatch both to currentBufferView() and, if that fails,
1204 // to documentBufferView(); same as we do now for current Buffer and
1205 // document Buffer. Ideally those LFUN should go to Buffer as they
1206 // operate on the full Buffer and the cursor is only needed either for
1207 // an Undo record or to restore a cursor position. But we don't know
1208 // how to do that inside Buffer of course.
1209 case LFUN_BUFFER_PARAMS_APPLY:
1210 case LFUN_LAYOUT_MODULES_CLEAR:
1211 case LFUN_LAYOUT_MODULE_ADD:
1212 case LFUN_LAYOUT_RELOAD:
1213 case LFUN_TEXTCLASS_APPLY:
1214 case LFUN_TEXTCLASS_LOAD:
1215 flag.setEnabled(!buffer_.isReadonly());
1219 // We do not use the LyXAction flag for readonly because Undo sets the
1220 // buffer clean/dirty status by itself.
1221 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasUndoStack());
1224 // We do not use the LyXAction flag for readonly because Redo sets the
1225 // buffer clean/dirty status by itself.
1226 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasRedoStack());
1228 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1229 case LFUN_FILE_INSERT_PLAINTEXT: {
1230 docstring const & fname = cmd.argument();
1231 if (!FileName::isAbsolute(to_utf8(fname))) {
1232 flag.message(_("Absolute filename expected."));
1235 flag.setEnabled(cur.inTexted());
1238 case LFUN_FILE_INSERT:
1239 case LFUN_BOOKMARK_SAVE:
1240 // FIXME: Actually, these LFUNS should be moved to Text
1241 flag.setEnabled(cur.inTexted());
1244 case LFUN_FONT_STATE:
1245 case LFUN_LABEL_INSERT:
1246 case LFUN_INFO_INSERT:
1247 case LFUN_PARAGRAPH_GOTO:
1248 case LFUN_NOTE_NEXT:
1249 case LFUN_REFERENCE_NEXT:
1250 case LFUN_WORD_FIND:
1251 case LFUN_WORD_FIND_FORWARD:
1252 case LFUN_WORD_FIND_BACKWARD:
1253 case LFUN_WORD_REPLACE:
1256 case LFUN_MARK_TOGGLE:
1257 case LFUN_SEARCH_STRING_SET:
1258 case LFUN_SCREEN_RECENTER:
1259 case LFUN_SCREEN_SHOW_CURSOR:
1260 case LFUN_BIBTEX_DATABASE_ADD:
1261 case LFUN_BIBTEX_DATABASE_DEL:
1262 case LFUN_BIBTEX_DATABASE_LIST:
1263 case LFUN_STATISTICS:
1264 case LFUN_KEYMAP_OFF:
1265 case LFUN_KEYMAP_PRIMARY:
1266 case LFUN_KEYMAP_SECONDARY:
1267 case LFUN_KEYMAP_TOGGLE:
1268 case LFUN_INSET_SELECT_ALL:
1269 flag.setEnabled(true);
1272 case LFUN_GRAPHICS_UNIFY:
1273 flag.setEnabled(cur.countInsetsInSelection(GRAPHICS_CODE)>1);
1276 case LFUN_WORD_FINDADV: {
1277 FindAndReplaceOptions opt;
1278 istringstream iss(to_utf8(cmd.argument()));
1280 flag.setEnabled(opt.repl_buf_name.empty()
1281 || !buffer_.isReadonly());
1285 case LFUN_LABEL_GOTO:
1286 flag.setEnabled(!cmd.argument().empty()
1287 || getInsetByCode<InsetRef>(cur, REF_CODE)
1288 || getInsetByCode<InsetMathRef>(cur, MATH_REF_CODE));
1291 case LFUN_CHANGES_MERGE:
1292 case LFUN_CHANGE_NEXT:
1293 case LFUN_CHANGE_PREVIOUS:
1294 case LFUN_ALL_CHANGES_ACCEPT:
1295 case LFUN_ALL_CHANGES_REJECT:
1296 flag.setEnabled(buffer_.areChangesPresent());
1299 case LFUN_SCREEN_UP:
1300 case LFUN_SCREEN_DOWN:
1302 case LFUN_SCREEN_UP_SELECT:
1303 case LFUN_SCREEN_DOWN_SELECT:
1304 case LFUN_INSET_FORALL:
1305 flag.setEnabled(true);
1308 case LFUN_LAYOUT_TABULAR:
1309 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1313 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1316 case LFUN_LAYOUT_PARAGRAPH:
1317 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1320 case LFUN_BRANCH_ADD_INSERT:
1321 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1324 case LFUN_DIALOG_SHOW_NEW_INSET:
1325 // FIXME: this is wrong, but I do not understand the
1327 if (cur.inset().lyxCode() == CAPTION_CODE)
1328 return cur.inset().getStatus(cur, cmd, flag);
1329 // FIXME we should consider passthru paragraphs too.
1330 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1333 case LFUN_CITATION_INSERT: {
1334 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1335 // FIXME: This could turn in a recursive hell.
1336 // Shouldn't we use Buffer::getStatus() instead?
1337 flag.setEnabled(lyx::getStatus(fr).enabled());
1340 case LFUN_INSET_APPLY: {
1341 string const name = cmd.getArg(0);
1342 Inset * inset = editedInset(name);
1344 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1345 if (!inset->getStatus(cur, fr, flag)) {
1346 // Every inset is supposed to handle this
1347 LASSERT(false, break);
1350 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1351 flag = lyx::getStatus(fr);
1357 flag.setEnabled(cur.selection());
1360 case LFUN_STATISTICS_REFERENCE_CLAMP: {
1361 // disable optitem reset if clamp not used
1362 if (cmd.argument() == "reset" && d->stats_ref_value_c_ == 0) {
1363 flag.setEnabled(false);
1366 flag.setEnabled(true);
1379 Inset * BufferView::editedInset(string const & name) const
1381 map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1382 return it == d->edited_insets_.end() ? nullptr : it->second;
1386 void BufferView::editInset(string const & name, Inset * inset)
1389 d->edited_insets_[name] = inset;
1391 d->edited_insets_.erase(name);
1395 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1397 LYXERR(Debug::ACTION, "BufferView::dispatch: cmd: " << cmd);
1399 string const argument = to_utf8(cmd.argument());
1400 Cursor & cur = d->cursor_;
1403 // Don't dispatch function that does not apply to internal buffers.
1404 if (buffer_.isInternal()
1405 && lyxaction.funcHasFlag(cmd.action(), LyXAction::NoInternal))
1408 // We'll set this back to false if need be.
1409 bool dispatched = true;
1410 buffer_.undo().beginUndoGroup();
1412 FuncCode const act = cmd.action();
1415 case LFUN_BUFFER_PARAMS_APPLY: {
1416 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
1417 cur.recordUndoBufferParams();
1418 istringstream ss(to_utf8(cmd.argument()));
1421 int const unknown_tokens = buffer_.readHeader(lex);
1422 if (unknown_tokens != 0) {
1423 LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1424 << unknown_tokens << " unknown token"
1425 << (unknown_tokens == 1 ? "" : "s"));
1427 updateDocumentClass(olddc);
1429 // We are most certainly here because of a change in the document
1430 // It is then better to make sure that all dialogs are in sync with
1431 // current document settings.
1432 dr.screenUpdate(Update::Force | Update::FitCursor);
1433 dr.forceBufferUpdate();
1437 case LFUN_LAYOUT_MODULES_CLEAR: {
1438 // FIXME: this modifies the document in cap::switchBetweenClasses
1439 // without calling recordUndo. Fix this before using
1440 // recordUndoBufferParams().
1441 cur.recordUndoFullBuffer();
1442 buffer_.params().clearLayoutModules();
1443 makeDocumentClass();
1444 dr.screenUpdate(Update::Force);
1445 dr.forceBufferUpdate();
1449 case LFUN_LAYOUT_MODULE_ADD: {
1450 BufferParams const & params = buffer_.params();
1451 if (!params.layoutModuleCanBeAdded(argument)) {
1452 LYXERR0("Module `" << argument <<
1453 "' cannot be added due to failed requirements or "
1454 "conflicts with installed modules.");
1457 // FIXME: this modifies the document in cap::switchBetweenClasses
1458 // without calling recordUndo. Fix this before using
1459 // recordUndoBufferParams().
1460 cur.recordUndoFullBuffer();
1461 buffer_.params().addLayoutModule(argument);
1462 makeDocumentClass();
1463 dr.screenUpdate(Update::Force);
1464 dr.forceBufferUpdate();
1468 case LFUN_TEXTCLASS_APPLY: {
1469 // since this shortcircuits, the second call is made only if
1471 bool const success =
1472 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1473 LayoutFileList::get().load(argument, buffer_.filePath());
1475 docstring s = bformat(_("The document class `%1$s' "
1476 "could not be loaded."), from_utf8(argument));
1477 frontend::Alert::error(_("Could not load class"), s);
1481 LayoutFile const * old_layout = buffer_.params().baseClass();
1482 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1484 if (old_layout == new_layout)
1488 // Save the old, possibly modular, layout for use in conversion.
1489 // FIXME: this modifies the document in cap::switchBetweenClasses
1490 // without calling recordUndo. Fix this before using
1491 // recordUndoBufferParams().
1492 cur.recordUndoFullBuffer();
1493 buffer_.params().setBaseClass(argument, buffer_.layoutPos());
1494 makeDocumentClass();
1495 dr.screenUpdate(Update::Force);
1496 dr.forceBufferUpdate();
1500 case LFUN_TEXTCLASS_LOAD: {
1501 // since this shortcircuits, the second call is made only if
1503 bool const success =
1504 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1505 LayoutFileList::get().load(argument, buffer_.filePath());
1507 docstring s = bformat(_("The document class `%1$s' "
1508 "could not be loaded."), from_utf8(argument));
1509 frontend::Alert::error(_("Could not load class"), s);
1514 case LFUN_LAYOUT_RELOAD: {
1515 LayoutFileIndex bc = buffer_.params().baseClassID();
1516 LayoutFileList::get().reset(bc);
1517 buffer_.params().setBaseClass(bc, buffer_.layoutPos());
1518 makeDocumentClass();
1519 dr.screenUpdate(Update::Force);
1520 dr.forceBufferUpdate();
1525 dr.setMessage(_("Undo"));
1526 cur.clearSelection();
1527 // We need to find out if the bibliography information
1528 // has changed. See bug #11055.
1529 // So these should not be references...
1530 string const engine = buffer().params().citeEngine();
1531 CiteEngineType const enginetype = buffer().params().citeEngineType();
1532 if (!cur.undoAction())
1533 dr.setMessage(_("No further undo information"));
1535 dr.screenUpdate(Update::Force | Update::FitCursor);
1536 dr.forceBufferUpdate();
1537 resetInlineCompletionPos();
1538 if (buffer().params().citeEngine() != engine ||
1539 buffer().params().citeEngineType() != enginetype)
1540 buffer().invalidateCiteLabels();
1546 dr.setMessage(_("Redo"));
1547 cur.clearSelection();
1548 // We need to find out if the bibliography information
1549 // has changed. See bug #11055.
1550 // So these should not be references...
1551 string const engine = buffer().params().citeEngine();
1552 CiteEngineType const enginetype = buffer().params().citeEngineType();
1553 if (!cur.redoAction())
1554 dr.setMessage(_("No further redo information"));
1556 dr.screenUpdate(Update::Force | Update::FitCursor);
1557 dr.forceBufferUpdate();
1558 resetInlineCompletionPos();
1559 if (buffer().params().citeEngine() != engine ||
1560 buffer().params().citeEngineType() != enginetype)
1561 buffer().invalidateCiteLabels();
1566 case LFUN_FONT_STATE:
1567 dr.setMessage(cur.currentState(false));
1570 case LFUN_BOOKMARK_SAVE:
1571 dr.screenUpdate(Update::Force);
1572 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1575 case LFUN_LABEL_GOTO: {
1576 docstring label = cmd.argument();
1577 if (label.empty()) {
1579 getInsetByCode<InsetRef>(cur, REF_CODE);
1581 label = inset->getParam("reference");
1582 // persistent=false: use temp_bookmark
1586 if (!label.empty()) {
1588 // at the moment, this is redundant, since gotoLabel will
1589 // eventually call LFUN_PARAGRAPH_GOTO, but it seems best
1591 dr.screenUpdate(Update::Force | Update::FitCursor);
1593 InsetMathRef * minset =
1594 getInsetByCode<InsetMathRef>(cur, MATH_REF_CODE);
1596 lyx::dispatch(FuncRequest(LFUN_LABEL_GOTO,
1597 minset->getTarget()));
1602 case LFUN_PARAGRAPH_GOTO: {
1603 int const id = convert<int>(cmd.getArg(0));
1604 pos_type const pos = convert<int>(cmd.getArg(1));
1607 string const str_id_end = cmd.getArg(2);
1608 string const str_pos_end = cmd.getArg(3);
1610 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1611 b = theBufferList().next(b)) {
1614 curs.setCursor(b->getParFromID(id));
1616 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1620 LYXERR(Debug::INFO, "Paragraph " << curs.paragraph().id()
1621 << " found in buffer `"
1622 << b->absFileName() << "'.");
1624 if (b == &buffer_) {
1626 if (str_id_end.empty() || str_pos_end.empty()) {
1629 mouseSetCursor(curs);
1632 int const id_end = convert<int>(str_id_end);
1633 pos_type const pos_end = convert<int>(str_pos_end);
1634 success = setCursorFromEntries({id, pos},
1637 if (success && scrollToCursor(d->cursor_, SCROLL_TOP))
1638 dr.screenUpdate(Update::Force);
1640 // Switch to other buffer view and resend cmd
1641 lyx::dispatch(FuncRequest(
1642 LFUN_BUFFER_SWITCH, b->absFileName()));
1650 case LFUN_NOTE_NEXT:
1651 if (gotoInset(this, { NOTE_CODE }, false))
1652 dr.screenUpdate(Update::Force);
1655 case LFUN_REFERENCE_NEXT: {
1656 if (gotoInset(this, { LABEL_CODE, REF_CODE }, true))
1657 dr.screenUpdate(Update::Force);
1661 case LFUN_CHANGE_NEXT:
1662 findNextChange(this);
1663 if (cur.inset().isTable())
1664 // In tables, there might be whole changed rows or columns
1666 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1667 dr.screenUpdate(Update::Force | Update::FitCursor);
1670 case LFUN_CHANGE_PREVIOUS:
1671 findPreviousChange(this);
1672 if (cur.inset().isTable())
1673 // In tables, there might be whole changed rows or columns
1675 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1676 dr.screenUpdate(Update::Force | Update::FitCursor);
1679 case LFUN_CHANGES_MERGE:
1680 if (findNextChange(this) || findPreviousChange(this)) {
1681 dr.screenUpdate(Update::Force | Update::FitCursor);
1682 dr.forceBufferUpdate();
1683 showDialog("changes");
1687 case LFUN_ALL_CHANGES_ACCEPT: {
1688 // select complete document
1690 cur.selHandle(true);
1691 buffer_.text().cursorBottom(cur);
1692 // accept everything in a single step to support atomic undo
1693 // temporarily disable track changes in order to end with really
1694 // no new (e.g., DPSM-caused) changes (see #7487)
1695 bool const track = buffer_.params().track_changes;
1696 buffer_.params().track_changes = false;
1697 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1698 buffer_.params().track_changes = track;
1700 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1701 dr.screenUpdate(Update::Force | Update::FitCursor);
1702 dr.forceBufferUpdate();
1706 case LFUN_ALL_CHANGES_REJECT: {
1707 // select complete document
1709 cur.selHandle(true);
1710 buffer_.text().cursorBottom(cur);
1711 // reject everything in a single step to support atomic undo
1712 // temporarily disable track changes in order to end with really
1713 // no new (e.g., DPSM-caused) changes (see #7487)
1714 bool const track = buffer_.params().track_changes;
1715 buffer_.params().track_changes = false;
1716 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1717 buffer_.params().track_changes = track;
1719 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1720 dr.screenUpdate(Update::Force | Update::FitCursor);
1721 dr.forceBufferUpdate();
1725 case LFUN_WORD_FIND_FORWARD:
1726 case LFUN_WORD_FIND_BACKWARD: {
1727 docstring searched_string;
1729 if (!cmd.argument().empty()) {
1730 setSearchRequestCache(cmd.argument());
1731 searched_string = cmd.argument();
1733 searched_string = searchRequestCache();
1736 if (searched_string.empty())
1739 docstring const data =
1740 find2string(searched_string, false, false,
1741 act == LFUN_WORD_FIND_FORWARD, false, false, false);
1742 bool found = lyxfind(this, FuncRequest(LFUN_WORD_FIND, data));
1744 dr.screenUpdate(Update::Force | Update::FitCursor);
1746 dr.setMessage(_("Search string not found!"));
1750 case LFUN_WORD_FIND: {
1751 docstring arg = cmd.argument();
1753 arg = searchRequestCache();
1755 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1758 if (lyxfind(this, FuncRequest(act, arg)))
1759 dr.screenUpdate(Update::Force | Update::FitCursor);
1761 dr.setMessage(_("Search string not found!"));
1763 setSearchRequestCache(arg);
1767 case LFUN_SEARCH_STRING_SET: {
1768 docstring pattern = cmd.argument();
1769 if (!pattern.empty()) {
1770 setSearchRequestCache(pattern);
1773 if (cur.selection())
1774 pattern = cur.selectionAsString(false);
1775 else if (!cur.inTexted())
1776 break; // not suitable for selectWord at cursor
1778 pos_type spos = cur.pos();
1779 cur.innerText()->selectWord(cur, WHOLE_WORD);
1780 pattern = cur.selectionAsString(false);
1781 cur.selection(false);
1784 setSearchRequestCache(pattern);
1788 case LFUN_WORD_REPLACE: {
1789 if (lyxreplace(this, cmd)) {
1790 dr.forceBufferUpdate();
1791 dr.screenUpdate(Update::Force | Update::FitCursor);
1794 dr.setMessage(_("Search string not found!"));
1798 case LFUN_WORD_FINDADV: {
1799 FindAndReplaceOptions opt;
1800 istringstream iss(to_utf8(cmd.argument()));
1802 if (findAdv(this, opt)) {
1803 dr.screenUpdate(Update::Force | Update::FitCursor);
1813 case LFUN_INDEX_TAG_ALL: {
1818 Inset * ins = cur.nextInset();
1819 if (!ins || ins->lyxCode() != INDEX_CODE)
1820 // not at index inset
1823 // clone the index inset
1825 new InsetIndex(static_cast<InsetIndex &>(*cur.nextInset()));
1826 // In order to avoid duplication, we compare the
1827 // LaTeX output if we find another index inset after
1829 odocstringstream oilatex;
1830 otexstream oits(oilatex);
1831 OutputParams rp(&cur.buffer()->params().encoding());
1832 ins->latex(oits, rp);
1833 cap::copyInsetToTemp(cur, cins);
1835 // move backwards into preceding word
1836 // skip over other index insets
1837 cur.backwardPosIgnoreCollapsed();
1839 if (cur.inset().lyxCode() == INDEX_CODE)
1841 else if (cur.prevInset() && cur.prevInset()->lyxCode() == INDEX_CODE)
1842 cur.backwardPosIgnoreCollapsed();
1846 if (!cur.inTexted()) {
1847 // Nothing to do here.
1848 setCursorFromInset(ins);
1851 // Get word or selection
1852 cur.text()->selectWord(cur, WHOLE_WORD);
1853 docstring const searched_string = cur.selectionAsString(false);
1854 if (searched_string.empty())
1856 // Start from the beginning
1857 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
1858 while (findOne(this, searched_string,
1859 false,// case sensitive
1860 true,// match whole word only
1862 false,//find deleted
1866 false// only selection
1868 cur.clearSelection();
1869 Inset * ains = cur.nextInset();
1870 if (ains && ains->lyxCode() == INDEX_CODE) {
1871 // We have an index inset.
1872 // Check whether it has the same
1873 // LaTeX content and move on if so.
1874 odocstringstream filatex;
1875 otexstream fits(filatex);
1876 ains->latex(fits, rp);
1877 if (oilatex.str() == filatex.str())
1880 // Paste the inset and possibly continue
1881 cap::pasteFromTemp(cursor(), cursor().buffer()->errorList("Paste"));
1883 // Go back to start position.
1884 setCursorFromInset(ins);
1885 dr.screenUpdate(cur.result().screenUpdate());
1886 if (cur.result().needBufferUpdate())
1887 dr.forceBufferUpdate();
1892 cur.clearSelection();
1893 dr.setMessage(from_utf8(N_("Mark off")));
1897 cur.clearSelection();
1899 dr.setMessage(from_utf8(N_("Mark on")));
1902 case LFUN_MARK_TOGGLE:
1903 cur.selection(false);
1906 dr.setMessage(from_utf8(N_("Mark removed")));
1909 dr.setMessage(from_utf8(N_("Mark set")));
1914 case LFUN_SCREEN_SHOW_CURSOR:
1918 case LFUN_SCREEN_RECENTER:
1922 case LFUN_BIBTEX_DATABASE_ADD: {
1923 Cursor tmpcur = cur;
1924 findInset(tmpcur, { BIBTEX_CODE }, false);
1925 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1928 if (inset->addDatabase(cmd.argument()))
1929 dr.forceBufferUpdate();
1934 case LFUN_BIBTEX_DATABASE_DEL: {
1935 Cursor tmpcur = cur;
1936 findInset(tmpcur, { BIBTEX_CODE }, false);
1937 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1940 if (inset->delDatabase(cmd.argument()))
1941 dr.forceBufferUpdate();
1946 case LFUN_GRAPHICS_UNIFY: {
1948 cur.recordUndoFullBuffer();
1950 DocIterator from, to;
1951 from = cur.selectionBegin();
1952 to = cur.selectionEnd();
1954 string const newId = cmd.getArg(0);
1955 bool fetchId = newId.empty(); //if we wait for groupId from first graphics inset
1957 InsetGraphicsParams grp_par;
1959 InsetGraphics::string2params(graphics::getGroupParams(buffer_, newId), buffer_, grp_par);
1961 if (!from.nextInset()) //move to closest inset
1962 from.forwardInset();
1964 while (!from.empty() && from < to) {
1965 Inset * inset = from.nextInset();
1968 InsetGraphics * ig = inset->asInsetGraphics();
1970 InsetGraphicsParams inspar = ig->getParams();
1975 grp_par.filename = inspar.filename;
1976 ig->setParams(grp_par);
1979 from.forwardInset();
1981 dr.screenUpdate(Update::Force); //needed if triggered from context menu
1985 case LFUN_BIBTEX_DATABASE_LIST: {
1986 docstring_list const & files = buffer_.getBibfiles();
1989 char const separator(os::path_separator());
1990 for (auto const & file : files) {
1994 result += separator;
1996 FileName const fn = buffer_.getBibfilePath(file);
1997 string const path = fn.realPath();
1998 result += from_utf8(os::external_path(path));
2000 dr.setMessage(result);
2004 case LFUN_STATISTICS: {
2005 DocIterator from, to;
2006 if (cur.selection()) {
2007 from = cur.selectionBegin();
2008 to = cur.selectionEnd();
2010 from = doc_iterator_begin(&buffer_);
2011 to = doc_iterator_end(&buffer_);
2013 buffer_.updateStatistics(from, to);
2014 int const words = buffer_.wordCount();
2015 int const chars = buffer_.charCount(false);
2016 int const chars_blanks = buffer_.charCount(true);
2018 if (cur.selection())
2019 message = _("Statistics for the selection:");
2021 message = _("Statistics for the document:");
2024 message += bformat(_("%1$d words"), words);
2026 message += _("One word");
2028 if (chars_blanks != 1)
2029 message += bformat(_("%1$d characters"), chars_blanks);
2031 message += _("One character");
2034 message += bformat(_("%1$d characters (no blanks)"), chars);
2036 message += _("One character (no blanks)");
2038 Alert::information(_("Statistics"), message);
2042 case LFUN_STATISTICS_REFERENCE_CLAMP: {
2043 d->stats_update_trigger_ = true;
2044 if (cmd.argument() == "reset") {
2045 d->stats_ref_value_w_ = d->stats_ref_value_c_ = d->stats_ref_value_nb_ = 0;
2049 DocIterator from, to;
2050 from = doc_iterator_begin(&buffer_);
2051 to = doc_iterator_end(&buffer_);
2052 buffer_.updateStatistics(from, to);
2054 d->stats_ref_value_w_ = buffer_.wordCount();
2055 d->stats_ref_value_c_ = buffer_.charCount(true);
2056 d->stats_ref_value_nb_ = buffer_.charCount(false);
2061 case LFUN_SCREEN_UP:
2062 case LFUN_SCREEN_DOWN: {
2063 Point p = getPos(cur);
2064 // This code has been commented out to enable to scroll down a
2065 // document, even if there are large insets in it (see bug #5465).
2066 /*if (p.y_ < 0 || p.y_ > height_) {
2067 // The cursor is off-screen so recenter before proceeding.
2071 int const scrolled = scroll(act == LFUN_SCREEN_UP
2072 ? -height_ : height_);
2073 if (act == LFUN_SCREEN_UP && scrolled > -height_)
2075 if (act == LFUN_SCREEN_DOWN && scrolled < height_)
2076 p = Point(width_, height_);
2077 bool const in_texted = cur.inTexted();
2078 cur.setCursor(doc_iterator_begin(cur.buffer()));
2079 cur.selHandle(false);
2080 // Force an immediate computation of metrics because we need it below
2082 processUpdateFlags(Update::Force);
2084 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
2085 true, act == LFUN_SCREEN_UP);
2086 //FIXME: what to do with cur.x_target()?
2087 bool update = in_texted && cur.bv().checkDepm(cur, old);
2090 if (update || cur.mark())
2091 dr.screenUpdate(Update::Force | Update::FitCursor);
2093 dr.forceBufferUpdate();
2098 string const scroll_type = cmd.getArg(0);
2099 int scroll_step = 0;
2100 if (scroll_type == "line")
2101 scroll_step = d->scrollbarParameters_.single_step;
2102 else if (scroll_type == "page")
2103 scroll_step = d->scrollbarParameters_.page_step;
2106 string const scroll_quantity = cmd.getArg(1);
2107 if (scroll_quantity == "up")
2108 scrollUp(scroll_step);
2109 else if (scroll_quantity == "down")
2110 scrollDown(scroll_step);
2112 int const scroll_value = convert<int>(scroll_quantity);
2114 scroll(scroll_step * scroll_value);
2116 dr.screenUpdate(Update::ForceDraw);
2117 dr.forceBufferUpdate();
2121 case LFUN_SCREEN_UP_SELECT: {
2122 // FIXME: why is the algorithm different from LFUN_SCREEN_UP?
2123 cur.selHandle(true);
2124 if (isTopScreen()) {
2125 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
2129 int y = getPos(cur).y_;
2130 int const ymin = y - height_ + defaultRowHeight();
2131 while (y > ymin && cur.up())
2135 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
2139 case LFUN_SCREEN_DOWN_SELECT: {
2140 // FIXME: why is the algorithm different from LFUN_SCREEN_DOWN?
2141 cur.selHandle(true);
2142 if (isBottomScreen()) {
2143 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
2147 int y = getPos(cur).y_;
2148 int const ymax = y + height_ - defaultRowHeight();
2149 while (y < ymax && cur.down())
2153 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
2158 case LFUN_INSET_SELECT_ALL: {
2159 // true if all cells are selected
2160 bool const all_selected = cur.depth() > 1
2161 && cur.selBegin().at_begin()
2162 && cur.selEnd().at_end();
2163 // true if some cells are selected
2164 bool const cells_selected = cur.depth() > 1
2165 && cur.selBegin().at_cell_begin()
2166 && cur.selEnd().at_cell_end();
2167 if (all_selected || (cells_selected && !cur.inset().isTable())) {
2168 // All the contents of the inset if selected, or only at
2169 // least one cell but inset is not a table.
2170 // Select the inset from outside.
2173 cur.selection(true);
2175 } else if (cells_selected) {
2176 // At least one complete cell is selected and inset is a table.
2182 cur.selection(true);
2183 cur.idx() = cur.lastidx();
2184 cur.pit() = cur.lastpit();
2185 cur.pos() = cur.lastpos();
2187 // select current cell
2191 cur.selection(true);
2192 cur.pit() = cur.lastpit();
2193 cur.pos() = cur.lastpos();
2195 cur.setCurrentFont();
2196 dr.screenUpdate(Update::Force);
2201 case LFUN_UNICODE_INSERT: {
2202 if (cmd.argument().empty())
2205 FuncCode code = cur.inset().currentMode() == Inset::MATH_MODE ?
2206 LFUN_MATH_INSERT : LFUN_SELF_INSERT;
2209 docstring const arg = from_utf8(cmd.getArg(i));
2213 LYXERR0("Not a hexstring: " << arg);
2217 char_type c = hexToInt(arg);
2218 if (c >= 32 && c < 0x10ffff) {
2219 LYXERR(Debug::KEY, "Inserting c: " << c);
2220 lyx::dispatch(FuncRequest(code, docstring(1, c)));
2228 // This would be in Buffer class if only Cursor did not
2229 // require a bufferview
2230 case LFUN_INSET_FORALL: {
2231 docstring const name = from_utf8(cmd.getArg(0));
2232 string const commandstr = cmd.getLongArg(1);
2233 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
2235 // an arbitrary number to limit number of iterations
2236 const int max_iter = 100000;
2238 Cursor & bvcur = d->cursor_;
2239 Cursor const savecur = bvcur;
2241 if (!bvcur.nextInset())
2242 bvcur.forwardInset();
2243 bvcur.beginUndoGroup();
2244 while(bvcur && iterations < max_iter) {
2245 Inset * const ins = bvcur.nextInset();
2248 docstring insname = ins->layoutName();
2249 while (!insname.empty()) {
2250 if (insname == name || name == from_utf8("*")) {
2251 lyx::dispatch(fr, dr);
2252 // we do not want to remember selection here
2253 bvcur.clearSelection();
2257 size_t const i = insname.rfind(':');
2258 if (i == string::npos)
2260 insname = insname.substr(0, i);
2262 // if we did not delete the inset, skip it
2263 if (!bvcur.nextInset() || bvcur.nextInset() == ins)
2264 bvcur.forwardInset();
2267 bvcur.fixIfBroken();
2268 /** This is a dummy undo record only to remember the cursor
2269 * that has just been set; this will be used on a redo action
2270 * (see ticket #10097)
2272 * FIXME: a better fix would be to have a way to set the
2273 * cursor value directly, but I am not sure it is worth it.
2276 bvcur.endUndoGroup();
2277 dr.screenUpdate(Update::Force);
2278 dr.forceBufferUpdate();
2280 if (iterations >= max_iter) {
2282 dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
2284 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
2289 case LFUN_BRANCH_ADD_INSERT: {
2290 docstring branch_name = from_utf8(cmd.getArg(0));
2291 if (branch_name.empty())
2292 if (!Alert::askForText(branch_name, _("Branch name")) ||
2293 branch_name.empty())
2296 DispatchResult drtmp;
2297 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
2298 if (drtmp.error()) {
2299 Alert::warning(_("Branch already exists"), drtmp.message());
2302 docstring const sep = buffer_.params().branchlist().separator();
2303 for (docstring const & branch : getVectorFromString(branch_name, sep))
2304 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch));
2308 case LFUN_KEYMAP_OFF:
2309 getIntl().keyMapOn(false);
2312 case LFUN_KEYMAP_PRIMARY:
2313 getIntl().keyMapPrim();
2316 case LFUN_KEYMAP_SECONDARY:
2317 getIntl().keyMapSec();
2320 case LFUN_KEYMAP_TOGGLE:
2321 getIntl().toggleKeyMap();
2324 case LFUN_DIALOG_SHOW_NEW_INSET: {
2325 string const name = cmd.getArg(0);
2326 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2327 if (decodeInsetParam(name, data, buffer_))
2328 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
2330 lyxerr << "Inset type '" << name <<
2331 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
2335 case LFUN_CITATION_INSERT: {
2336 if (argument.empty()) {
2337 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
2340 // we can have one optional argument, delimited by '|'
2341 // citation-insert <key>|<text_before>
2342 // this should be enhanced to also support text_after
2343 // and citation style
2344 string arg = argument;
2346 if (contains(argument, "|")) {
2347 arg = token(argument, '|', 0);
2348 opt1 = token(argument, '|', 1);
2351 // if our cursor is directly in front of or behind a citation inset,
2352 // we will instead add the new key to it.
2353 Inset * inset = cur.nextInset();
2354 if (!inset || inset->lyxCode() != CITE_CODE)
2355 inset = cur.prevInset();
2356 if (inset && inset->lyxCode() == CITE_CODE) {
2357 InsetCitation * icite = static_cast<InsetCitation *>(inset);
2358 if (icite->addKey(arg)) {
2359 dr.forceBufferUpdate();
2360 dr.screenUpdate(Update::FitCursor | Update::SinglePar);
2362 LYXERR0("Discarding optional argument to citation-insert.");
2367 InsetCommandParams icp(CITE_CODE);
2368 icp["key"] = from_utf8(arg);
2370 icp["before"] = from_utf8(opt1);
2372 from_ascii(InsetCitation::last_literal ? "true" : "false");
2373 string icstr = InsetCommand::params2string(icp);
2374 FuncRequest fr(LFUN_INSET_INSERT, icstr);
2377 // if the request comes from the LyX server, then we
2378 // return a list of the undefined keys, in case some
2379 // action could be taken.
2380 if (cmd.origin() != FuncRequest::LYXSERVER)
2383 vector<docstring> keys = getVectorFromString(from_utf8(arg));
2384 vector<docstring>::iterator it = keys.begin();
2385 vector<docstring>::const_iterator end = keys.end();
2387 BiblioInfo const & bibInfo = buffer_.masterBibInfo();
2388 const BiblioInfo::const_iterator bibEnd = bibInfo.end();
2390 if (bibInfo.find(*it) != bibEnd) {
2391 it = keys.erase(it);
2396 dr.setMessage(getStringFromVector(keys));
2401 case LFUN_INSET_APPLY: {
2402 string const name = cmd.getArg(0);
2403 Inset * inset = editedInset(name);
2405 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
2409 // put cursor in front of inset.
2410 if (!setCursorFromInset(inset)) {
2411 LASSERT(false, break);
2414 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
2415 inset->dispatch(cur, fr);
2416 dr.screenUpdate(cur.result().screenUpdate());
2417 if (cur.result().needBufferUpdate())
2418 dr.forceBufferUpdate();
2423 // The change of language of buffer belongs to the Buffer class.
2424 // We have to do it here because we need a cursor for Undo.
2425 // When Undo::recordUndoBufferParams() is implemented someday
2426 // LFUN_BUFFER_LANGUAGE should be handled by the Buffer class.
2427 case LFUN_BUFFER_LANGUAGE: {
2428 Language const * oldL = buffer_.params().language;
2429 Language const * newL = languages.getLanguage(argument);
2430 if (!newL || oldL == newL)
2432 if (oldL->rightToLeft() == newL->rightToLeft()) {
2433 cur.recordUndoFullBuffer();
2434 buffer_.changeLanguage(oldL, newL);
2435 cur.setCurrentFont();
2436 dr.forceBufferUpdate();
2441 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2442 case LFUN_FILE_INSERT_PLAINTEXT: {
2443 bool const as_paragraph = (act == LFUN_FILE_INSERT_PLAINTEXT_PARA);
2444 string const fname = to_utf8(cmd.argument());
2445 if (!FileName::isAbsolute(fname))
2446 dr.setMessage(_("Absolute filename expected."));
2448 insertPlaintextFile(FileName(fname), as_paragraph);
2453 // With multi-cell table content, we pass down to the inset
2454 if (cur.inTexted() && cur.selection()
2455 && cur.selectionBegin().idx() != cur.selectionEnd().idx()) {
2456 buffer_.dispatch(cmd, dr);
2457 dispatched = dr.dispatched();
2460 cap::copySelection(cur);
2461 cur.message(_("Copy"));
2465 // OK, so try the Buffer itself...
2466 buffer_.dispatch(cmd, dr);
2467 dispatched = dr.dispatched();
2471 buffer_.undo().endUndoGroup();
2472 dr.dispatched(dispatched);
2474 // NOTE: The code below is copied from Cursor::dispatch. If you
2475 // need to modify this, please update the other one too.
2477 // notify insets we just entered/left
2478 if (cursor() != old) {
2479 old.beginUndoGroup();
2481 bool badcursor = notifyCursorLeavesOrEnters(old, cursor());
2483 cursor().fixIfBroken();
2484 resetInlineCompletionPos();
2491 docstring BufferView::requestSelection()
2493 Cursor & cur = d->cursor_;
2495 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
2496 if (!cur.selection()) {
2497 d->xsel_cache_.set = false;
2501 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
2502 if (!d->xsel_cache_.set ||
2503 cur.top() != d->xsel_cache_.cursor ||
2504 cur.realAnchor().top() != d->xsel_cache_.anchor)
2506 d->xsel_cache_.cursor = cur.top();
2507 d->xsel_cache_.anchor = cur.realAnchor().top();
2508 d->xsel_cache_.set = cur.selection();
2509 return cur.selectionAsString(false);
2515 void BufferView::clearSelection()
2517 d->cursor_.clearSelection();
2518 // Clear the selection buffer. Otherwise a subsequent
2519 // middle-mouse-button paste would use the selection buffer,
2520 // not the more current external selection.
2521 cap::clearSelection();
2522 d->xsel_cache_.set = false;
2523 // The buffer did not really change, but this causes the
2524 // redraw we need because we cleared the selection above.
2525 buffer_.changed(false);
2529 void BufferView::resize(int width, int height)
2532 // Update metrics only if width has changed
2533 if (width != width_) {
2536 // Clear the paragraph height cache.
2537 d->par_height_.clear();
2538 // Redo the metrics.
2539 updateMetrics(true);
2541 // metrics is OK, full drawing is necessary now
2542 d->update_flags_ = (d->update_flags_ & ~Update::Force) | Update::ForceDraw;
2543 d->update_strategy_ = FullScreenUpdate;
2547 Inset const * BufferView::getCoveringInset(Text const & text,
2550 TextMetrics & tm = d->text_metrics_[&text];
2551 Inset * inset = tm.checkInsetHit(x, y);
2555 if (!inset->descendable(*this))
2556 // No need to go further down if the inset is not
2560 size_t cell_number = inset->nargs();
2561 // Check all the inner cell.
2562 for (size_t i = 0; i != cell_number; ++i) {
2563 Text const * inner_text = inset->getText(i);
2566 Inset const * inset_deeper =
2567 getCoveringInset(*inner_text, x, y);
2569 return inset_deeper;
2577 Inset const * BufferView::clickableMathInset(InsetMathNest const * inset,
2578 CoordCache::Insets const & inset_cache, int x, int y) const
2580 for (size_t i = 0; i < inset->nargs(); ++i) {
2581 MathData const & ar = inset->cell(i);
2582 for (size_t j = 0; j < ar.size(); ++j) {
2583 string const name = lyxerr.debugging(Debug::MATHED)
2584 ? insetName(ar[j].nucleus()->lyxCode())
2586 LYXERR(Debug::MATHED, "Checking inset: " << name);
2587 if (ar[j].nucleus()->clickable(*this, x, y)) {
2588 if (inset_cache.covers(ar[j].nucleus(), x, y)) {
2589 LYXERR(Debug::MATHED, "Clickable inset: "
2591 return ar[j].nucleus();
2594 InsetMathNest const * imn =
2595 ar[j].nucleus()->asNestInset();
2597 Inset const * inner =
2598 clickableMathInset(imn, inset_cache, x, y);
2608 void BufferView::updateHoveredInset() const
2610 // Get inset under mouse, if there is one.
2611 int const x = d->mouse_position_cache_.x_;
2612 int const y = d->mouse_position_cache_.y_;
2613 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
2614 if (covering_inset && covering_inset->asInsetMath()) {
2615 Inset const * inner_inset = clickableMathInset(
2616 covering_inset->asInsetMath()->asNestInset(),
2617 coordCache().getInsets(), x, y);
2619 covering_inset = inner_inset;
2622 d->clickable_inset_ = covering_inset && covering_inset->clickable(*this, x, y);
2624 if (covering_inset == d->last_inset_)
2625 // Same inset, no need to do anything...
2628 bool need_redraw = false;
2629 if (d->last_inset_) {
2630 // Remove the hint on the last hovered inset (if any).
2631 need_redraw |= d->last_inset_->setMouseHover(this, false);
2632 d->last_inset_ = nullptr;
2635 if (covering_inset && covering_inset->setMouseHover(this, true)) {
2637 // Only the insets that accept the hover state, do
2638 // clear the last_inset_, so only set the last_inset_
2639 // member if the hovered setting is accepted.
2640 d->last_inset_ = covering_inset;
2644 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
2645 << d->mouse_position_cache_.x_ << ", "
2646 << d->mouse_position_cache_.y_ << ")");
2648 d->update_strategy_ = DecorationUpdate;
2650 // This event (moving without mouse click) is not passed further.
2651 // This should be changed if it is further utilized.
2652 buffer_.changed(false);
2657 void BufferView::clearLastInset(Inset * inset) const
2659 if (d->last_inset_ != inset) {
2660 LYXERR0("Wrong last_inset!");
2663 d->last_inset_ = nullptr;
2667 bool BufferView::mouseSelecting() const
2669 return d->mouse_selecting_;
2673 int BufferView::stats_ref_value_w() const
2675 return d->stats_ref_value_w_;
2679 int BufferView::stats_ref_value_c() const
2681 return d->stats_ref_value_c_;
2685 int BufferView::stats_ref_value_nb() const
2687 return d->stats_ref_value_nb_;
2691 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
2693 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
2698 // This is only called for mouse related events including
2699 // LFUN_FILE_OPEN generated by drag-and-drop.
2700 FuncRequest cmd = cmd0;
2702 // Either the inset under the cursor or the
2703 // surrounding Text will handle this event.
2705 // make sure we stay within the screen...
2706 cmd.set_y(min(max(cmd.y(), -1), height_));
2708 d->mouse_position_cache_.x_ = cmd.x();
2709 d->mouse_position_cache_.y_ = cmd.y();
2711 d->mouse_selecting_ =
2712 cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::button1;
2714 if (cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
2715 updateHoveredInset();
2719 Cursor old = cursor();
2721 cur.push(buffer_.inset());
2722 cur.selection(d->cursor_.selection());
2724 // Build temporary cursor.
2725 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x(), cmd.y());
2727 // If inset is not editable, cur.pos() might point behind the
2728 // inset (depending on cmd.x(), cmd.y()). This is needed for
2729 // editing to fix bug 9628, but e.g. the context menu needs a
2730 // cursor in front of the inset.
2731 if ((inset->hasSettings() || !inset->contextMenuName().empty()
2732 || inset->lyxCode() == SEPARATOR_CODE) &&
2733 cur.nextInset() != inset && cur.prevInset() == inset)
2735 } else if (cur.inTexted() && cur.pos()
2736 && cur.paragraph().isEnvSeparator(cur.pos() - 1)) {
2737 // Always place cursor in front of a separator inset.
2741 // Put anchor at the same position.
2744 old.beginUndoGroup();
2746 // Try to dispatch to an non-editable inset near this position
2747 // via the temp cursor. If the inset wishes to change the real
2748 // cursor it has to do so explicitly by using
2749 // cur.bv().cursor() = cur; (or similar)
2751 inset->dispatch(cur, cmd);
2753 // Now dispatch to the temporary cursor. If the real cursor should
2754 // be modified, the inset's dispatch has to do so explicitly.
2755 if (!inset || !cur.result().dispatched())
2758 // Notify left insets
2760 bool badcursor = old.fixIfBroken() || cur.fixIfBroken();
2761 badcursor = badcursor || notifyCursorLeavesOrEnters(old, cur);
2763 cursor().fixIfBroken();
2768 // Do we have a selection?
2769 theSelection().haveSelection(cursor().selection());
2771 if (cur.needBufferUpdate() || buffer().needUpdate()) {
2772 cur.clearBufferUpdate();
2773 buffer().updateBuffer();
2776 // If the command has been dispatched,
2777 if (cur.result().dispatched() || cur.result().screenUpdate())
2778 processUpdateFlags(cur.result().screenUpdate());
2782 int BufferView::minVisiblePart()
2784 return 2 * defaultRowHeight();
2788 int BufferView::scroll(int pixels)
2791 return scrollDown(pixels);
2793 return scrollUp(-pixels);
2798 int BufferView::scrollDown(int pixels)
2800 Text * text = &buffer_.text();
2801 TextMetrics & tm = d->text_metrics_[text];
2802 int const ymax = height_ + pixels;
2804 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2805 int bottom_pos = last.second->bottom();
2806 if (lyxrc.scroll_below_document)
2807 bottom_pos += height_ - minVisiblePart();
2808 if (last.first + 1 == int(text->paragraphs().size())) {
2809 if (bottom_pos <= height_)
2811 pixels = min(pixels, bottom_pos - height_);
2814 if (bottom_pos > ymax)
2816 tm.newParMetricsDown();
2818 d->anchor_ypos_ -= pixels;
2823 int BufferView::scrollUp(int pixels)
2825 Text * text = &buffer_.text();
2826 TextMetrics & tm = d->text_metrics_[text];
2827 int ymin = - pixels;
2829 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2830 int top_pos = first.second->top();
2831 if (first.first == 0) {
2834 pixels = min(pixels, - top_pos);
2839 tm.newParMetricsUp();
2841 d->anchor_ypos_ += pixels;
2846 bool BufferView::setCursorFromRow(int row)
2848 TexRow::TextEntry start, end;
2849 tie(start,end) = buffer_.texrow().getEntriesFromRow(row);
2850 LYXERR(Debug::OUTFILE,
2851 "setCursorFromRow: for row " << row << ", TexRow has found "
2852 "start (id=" << start.id << ",pos=" << start.pos << "), "
2853 "end (id=" << end.id << ",pos=" << end.pos << ")");
2854 return setCursorFromEntries(start, end);
2858 bool BufferView::setCursorFromEntries(TexRow::TextEntry start,
2859 TexRow::TextEntry end)
2861 DocIterator dit_start, dit_end;
2862 tie(dit_start,dit_end) =
2863 TexRow::getDocIteratorsFromEntries(start, end, buffer_);
2866 // Setting selection start
2867 d->cursor_.clearSelection();
2868 setCursor(dit_start);
2869 // Setting selection end
2871 d->cursor_.resetAnchor();
2872 setCursorSelectionTo(dit_end);
2878 bool BufferView::setCursorFromInset(Inset const * inset)
2880 // are we already there?
2881 if (cursor().nextInset() == inset)
2884 // Inset is not at cursor position. Find it in the document.
2887 while (cur && cur.nextInset() != inset)
2898 void BufferView::gotoLabel(docstring const & label)
2901 bool have_inactive = false;
2902 for (Buffer const * buf : buffer().allRelatives()) {
2904 for (TocItem const & item : *buf->tocBackend().toc("label")) {
2905 if (label == item.str() && item.isOutput()) {
2906 lyx::dispatch(item.action());
2909 // If we find an inactive label, save it for the case
2910 // that no active one is there
2911 if (label == item.str() && !have_inactive) {
2912 have_inactive = true;
2913 action = item.action();
2917 // We only found an inactive label. Go there.
2919 lyx::dispatch(action);
2923 TextMetrics const & BufferView::textMetrics(Text const * t) const
2925 return const_cast<BufferView *>(this)->textMetrics(t);
2929 TextMetrics & BufferView::textMetrics(Text const * t)
2932 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
2933 if (tmc_it == d->text_metrics_.end()) {
2934 tmc_it = d->text_metrics_.emplace(std::piecewise_construct,
2935 std::forward_as_tuple(t),
2936 std::forward_as_tuple(this, const_cast<Text *>(t))).first;
2938 return tmc_it->second;
2942 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2945 return textMetrics(t).parMetrics(pit);
2949 int BufferView::workHeight() const
2955 void BufferView::setCursor(DocIterator const & dit)
2958 size_t const n = dit.depth();
2959 for (size_t i = 0; i < n; ++i)
2960 dit[i].inset().edit(d->cursor_, true);
2962 d->cursor_.setCursor(dit);
2963 d->cursor_.selection(false);
2964 d->cursor_.setCurrentFont();
2966 // It seems on general grounds as if this is probably needed, but
2967 // it is not yet clear.
2968 // See bug #7394 and r38388.
2969 // d->cursor.resetAnchor();
2973 void BufferView::setCursorSelectionTo(DocIterator const & dit)
2975 size_t const n = dit.depth();
2976 for (size_t i = 0; i < n; ++i)
2977 dit[i].inset().edit(d->cursor_, true);
2979 d->cursor_.selection(true);
2980 d->cursor_.setCursorSelectionTo(dit);
2981 d->cursor_.setCurrentFont();
2985 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2987 // Would be wrong to delete anything if we have a selection.
2988 if (cur.selection())
2991 bool need_anchor_change = false;
2992 bool changed = Text::deleteEmptyParagraphMechanism(cur, old,
2993 need_anchor_change);
2995 if (need_anchor_change)
3003 // we would rather not do this here, but it needs to be done before
3004 // the changed() signal is sent.
3005 buffer_.updateBuffer();
3007 buffer_.changed(true);
3012 bool BufferView::mouseSetCursor(Cursor & cur, bool const select)
3014 LASSERT(&cur.bv() == this, return false);
3017 // this event will clear selection so we save selection for
3018 // persistent selection
3019 cap::saveSelection(cursor());
3021 d->cursor_.macroModeClose();
3022 // If a macro has been finalized, the cursor might have been broken
3025 // Has the cursor just left the inset?
3026 bool const leftinset = (&d->cursor_.inset() != &cur.inset());
3028 d->cursor_.fixIfBroken();
3030 // do the dEPM magic if needed
3031 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
3032 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
3033 // the leftinset bool would not be necessary (badcursor instead).
3034 bool update = leftinset;
3037 d->cursor_.setSelection();
3038 d->cursor_.setCursorSelectionTo(cur);
3040 if (d->cursor_.inTexted())
3041 update |= checkDepm(cur, d->cursor_);
3042 d->cursor_.resetAnchor();
3043 d->cursor_.setCursor(cur);
3044 d->cursor_.clearSelection();
3046 d->cursor_.boundary(cur.boundary());
3047 d->cursor_.finishUndo();
3048 d->cursor_.setCurrentFont();
3050 cur.forceBufferUpdate();
3055 void BufferView::putSelectionAt(DocIterator const & cur,
3056 int length, bool backwards)
3058 d->cursor_.clearSelection();
3064 d->cursor_.pos() += length;
3065 d->cursor_.setSelection(d->cursor_, -length);
3067 d->cursor_.setSelection(d->cursor_, length);
3072 void BufferView::setSelection(DocIterator const & from,
3073 DocIterator const & to)
3075 if (from.pit() != to.pit()) {
3076 // there are multiple paragraphs in selection
3077 cursor().setCursor(from);
3078 cursor().clearSelection();
3079 cursor().selection(true);
3080 cursor().setCursor(to);
3081 cursor().selection(true);
3083 // only single paragraph
3084 int const size = to.pos() - from.pos();
3085 putSelectionAt(from, size, false);
3087 processUpdateFlags(Update::Force | Update::FitCursor);
3091 bool BufferView::selectIfEmpty(DocIterator & cur)
3093 if ((cur.inTexted() && !cur.paragraph().empty())
3094 || (cur.inMathed() && !cur.cell().empty()))
3097 pit_type const beg_pit = cur.pit();
3099 // The paragraph associated to this item isn't
3100 // the first one, so it can be selected
3103 // We have to resort to select the space between the
3104 // end of this item and the begin of the next one
3108 // If it is the only item in the document,
3109 // nothing can be selected
3112 pit_type const end_pit = cur.pit();
3113 pos_type const end_pos = cur.pos();
3114 d->cursor_.clearSelection();
3116 d->cursor_.setCursor(cur);
3117 d->cursor_.pit() = beg_pit;
3118 d->cursor_.pos() = 0;
3119 d->cursor_.selection(false);
3120 d->cursor_.resetAnchor();
3121 d->cursor_.pit() = end_pit;
3122 d->cursor_.pos() = end_pos;
3123 d->cursor_.setSelection();
3128 Cursor & BufferView::cursor()
3134 Cursor const & BufferView::cursor() const
3140 bool BufferView::singleParUpdate()
3142 CursorSlice const & its = d->cursor_.innerTextSlice();
3143 pit_type const pit = its.pit();
3144 TextMetrics & tm = textMetrics(its.text());
3145 Dimension const old_dim = tm.parMetrics(pit).dim();
3147 // make sure inline completion pointer is ok
3148 if (d->inlineCompletionPos_.fixIfBroken())
3149 d->inlineCompletionPos_ = DocIterator();
3151 /* Try to rebreak only the paragraph containing the cursor (if
3152 * this paragraph contains insets etc., rebreaking will
3153 * recursively descend). We need a full redraw if either
3154 * 1/ the height has changed
3156 * 2/ the width has changed and it was equal to the textmetrics
3157 * width; the goal is to catch the case of a one-row inset that
3158 * grows with its contents, but optimize the case of typing at
3159 * the end of a mmultiple-row paragraph.
3161 * NOTE: if only the height has changed, then it should be
3162 * possible to update all metrics at minimal cost. However,
3163 * since this is risky, we do not try that right now.
3165 tm.redoParagraph(pit);
3166 ParagraphMetrics & pm = tm.parMetrics(pit);
3167 if (pm.height() != old_dim.height()
3168 || (pm.width() != old_dim.width() && old_dim.width() == tm.width())) {
3169 // Paragraph height or width has changed so we cannot proceed
3170 // to the singlePar optimisation.
3171 LYXERR(Debug::PAINTING, "SinglePar optimization failed.");
3174 // Since position() points to the baseline of the first row, we
3175 // may have to update it. See ticket #11601 for an example where
3176 // the height does not change but the ascent does.
3177 pm.setPosition(pm.position() - old_dim.ascent() + pm.ascent());
3179 tm.updatePosCache(pit);
3181 LYXERR(Debug::PAINTING, "\ny1: " << pm.top() << " y2: " << pm.bottom()
3182 << " pit: " << pit << " singlepar: 1");
3187 void BufferView::updateMetrics()
3189 updateMetrics(true);
3190 // metrics is done, full drawing is necessary now
3191 d->update_flags_ = (d->update_flags_ & ~Update::Force) | Update::ForceDraw;
3192 d->update_strategy_ = FullScreenUpdate;
3196 void BufferView::updateMetrics(bool force)
3201 //LYXERR0("updateMetrics " << _v_(force));
3203 Text & buftext = buffer_.text();
3204 pit_type const lastpit = int(buftext.paragraphs().size()) - 1;
3207 // Clear out the position cache in case of full screen redraw,
3208 d->coord_cache_.clear();
3209 d->math_rows_.clear();
3211 // Clear out paragraph metrics to avoid having invalid metrics
3212 // in the cache from paragraphs not relayouted below. The
3213 // complete text metrics will be redone.
3214 d->text_metrics_.clear();
3217 // This should not be moved earlier
3218 TextMetrics & tm = textMetrics(&buftext);
3220 // make sure inline completion pointer is ok
3221 if (d->inlineCompletionPos_.fixIfBroken())
3222 d->inlineCompletionPos_ = DocIterator();
3224 if (d->anchor_pit_ > lastpit)
3225 // The anchor pit must have been deleted...
3226 d->anchor_pit_ = lastpit;
3228 // Update metrics around the anchor
3229 tm.updateMetrics(d->anchor_pit_, d->anchor_ypos_, height_);
3231 // Check that the end of the document is not too high
3232 int const min_visible = lyxrc.scroll_below_document ? minVisiblePart() : height_;
3233 if (tm.last().first == lastpit && tm.last().second->hasPosition()
3234 && tm.last().second->bottom() < min_visible) {
3235 d->anchor_ypos_ += min_visible - tm.last().second->bottom();
3236 LYXERR(Debug::SCROLLING, "Too high, adjusting anchor ypos to " << d->anchor_ypos_);
3237 tm.updateMetrics(d->anchor_pit_, d->anchor_ypos_, height_);
3240 // Check that the start of the document is not too low
3241 if (tm.first().first == 0 && tm.first().second->hasPosition()
3242 && tm.first().second->top() > 0) {
3243 d->anchor_ypos_ -= tm.first().second->top();
3244 LYXERR(Debug::SCROLLING, "Too low, adjusting anchor ypos to " << d->anchor_ypos_);
3245 tm.updateMetrics(d->anchor_pit_, d->anchor_ypos_, height_);
3248 /* FIXME: do we want that? It avoids potential issues with old
3249 * paragraphs that should have been recomputed but have not, at
3250 * the price of potential extra metrics computation. I do not
3251 * think that the performance gain is high, so that for now the
3252 * extra paragraphs are removed
3254 // Remove paragraphs that are outside of screen
3255 while(!tm.first().second->hasPosition() || tm.first().second->bottom() <= 0) {
3256 //LYXERR0("Forget pit: " << tm.first().first);
3257 tm.forget(tm.first().first);
3259 while(!tm.last().second->hasPosition() || tm.last().second->top() > height_) {
3260 //LYXERR0("Forget pit: " << tm.first().first);
3261 tm.forget(tm.last().first);
3264 /* FIXME: if paragraphs outside of the screen are not removed
3265 * above, one has to search for the first visible one here */
3266 // Normalize anchor for next time
3267 if (d->anchor_pit_ != tm.first().first
3268 || d->anchor_ypos_ != tm.first().second->position()) {
3269 LYXERR(Debug::PAINTING, __func__ << ": Found new anchor pit = " << tm.first().first
3270 << " anchor ypos = " << tm.first().second->position()
3271 << " (was " << d->anchor_pit_ << ", " << d->anchor_ypos_ << ")");
3272 d->anchor_pit_ = tm.first().first;
3273 d->anchor_ypos_ = tm.first().second->position();
3276 // Now update the positions of insets in the cache.
3279 if (lyxerr.debugging(Debug::WORKAREA)) {
3280 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
3281 d->coord_cache_.dump();
3286 void BufferView::updatePosCache()
3288 // this is the "nodraw" drawing stage: only set the positions of the
3289 // insets in metrics cache.
3290 frontend::NullPainter np;
3295 void BufferView::insertLyXFile(FileName const & fname, bool const ignorelang)
3297 LASSERT(d->cursor_.inTexted(), return);
3299 // Get absolute path of file and add ".lyx"
3300 // to the filename if necessary
3301 FileName filename = fileSearch(string(), fname.absFileName(), "lyx");
3303 docstring const disp_fn = makeDisplayPath(filename.absFileName());
3304 // emit message signal.
3305 message(bformat(_("Inserting document %1$s..."), disp_fn));
3308 Buffer buf(filename.absFileName(), false);
3309 if (buf.loadLyXFile() == Buffer::ReadSuccess) {
3310 ErrorList & el = buffer_.errorList("Parse");
3311 // Copy the inserted document error list into the current buffer one.
3312 el = buf.errorList("Parse");
3313 ParagraphList & pars = buf.paragraphs();
3315 // set main language of imported file to context language
3316 buf.changeLanguage(buf.language(), d->cursor_.getFont().language());
3317 buffer_.undo().recordUndo(d->cursor_);
3318 cap::replaceSelection(d->cursor_);
3319 cap::pasteParagraphList(d->cursor_, pars,
3320 buf.params().documentClassPtr(),
3321 buf.params().authors(), el);
3322 res = _("Document %1$s inserted.");
3324 res = _("Could not insert document %1$s");
3327 buffer_.changed(true);
3328 // emit message signal.
3329 message(bformat(res, disp_fn));
3333 Point BufferView::coordOffset(DocIterator const & dit) const
3339 // Addup contribution of nested insets, from inside to outside,
3340 // keeping the outer paragraph for a special handling below
3341 for (size_t i = dit.depth() - 1; i >= 1; --i) {
3342 CursorSlice const & sl = dit[i];
3346 // get relative position inside sl.inset()
3347 sl.inset().cursorPos(*this, sl, dit.boundary() && (i + 1 == dit.depth()), xx, yy);
3349 // Make relative position inside of the edited inset relative to sl.inset()
3353 // In case of an RTL inset, the edited inset will be positioned to the left
3356 bool boundary_i = dit.boundary() && i + 1 == dit.depth();
3357 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
3362 // remember width for the case that sl.inset() is positioned in an RTL inset
3363 lastw = sl.inset().dimension(*this).wid;
3365 //lyxerr << "Cursor::getPos, i: "
3366 // << i << " x: " << xx << " y: " << y << endl;
3369 // Add contribution of initial rows of outermost paragraph
3370 CursorSlice const & sl = dit[0];
3371 TextMetrics const & tm = textMetrics(sl.text());
3372 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
3374 LBUFERR(!pm.rows().empty());
3375 y -= pm.rows()[0].ascent();
3377 // FIXME: document this mess
3379 if (sl.pos() > 0 && dit.depth() == 1) {
3381 if (pos && dit.boundary())
3383 // lyxerr << "coordOffset: boundary:" << dit.boundary() << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
3384 rend = pm.pos2row(pos);
3386 rend = pm.pos2row(sl.pos());
3388 size_t rend = pm.pos2row(sl.pos());
3390 for (size_t rit = 0; rit != rend; ++rit)
3391 y += pm.rows()[rit].height();
3392 y += pm.rows()[rend].ascent();
3394 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
3396 // Make relative position from the nested inset now bufferview absolute.
3397 int xx = bottom_tm.cursorX(dit.bottom(), dit.boundary() && dit.depth() == 1);
3400 // In the RTL case place the nested inset at the left of the cursor in
3401 // the outer paragraph
3402 bool boundary_1 = dit.boundary() && 1 == dit.depth();
3403 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
3411 Point BufferView::getPos(DocIterator const & dit) const
3413 if (!paragraphVisible(dit))
3414 return Point(-1, -1);
3416 CursorSlice const & bot = dit.bottom();
3417 TextMetrics const & tm = textMetrics(bot.text());
3419 // offset from outer paragraph
3420 Point p = coordOffset(dit);
3421 p.y_ += tm.parMetrics(bot.pit()).position();
3426 bool BufferView::paragraphVisible(DocIterator const & dit) const
3428 CursorSlice const & bot = dit.bottom();
3429 TextMetrics const & tm = textMetrics(bot.text());
3431 return tm.contains(bot.pit());
3435 void BufferView::caretPosAndDim(Point & p, Dimension & dim) const
3437 Cursor const & cur = cursor();
3438 if (cur.inMathed() && hasMathRow(&cur.cell())) {
3439 MathRow const & mrow = mathRow(&cur.cell());
3440 dim = mrow.caret_dim;
3442 Font const font = cur.real_current_font;
3443 frontend::FontMetrics const & fm = theFontMetrics(font);
3444 // lineWidth() can be 0 to mean 'thin line' on HiDpi, but the
3445 // caret drawing code is not prepared for that.
3446 dim.wid = max(fm.lineWidth(), 1);
3447 dim.asc = fm.maxAscent();
3448 dim.des = fm.maxDescent();
3450 if (lyxrc.cursor_width > 0)
3451 dim.wid = lyxrc.cursor_width;
3454 // center fat carets horizontally
3455 p.x_ -= dim.wid / 2;
3461 void BufferView::buildCaretGeometry(bool complet)
3465 caretPosAndDim(p, dim);
3467 Cursor const & cur = d->cursor_;
3468 Font const & realfont = cur.real_current_font;
3469 frontend::FontMetrics const & fm = theFontMetrics(realfont.fontInfo());
3470 bool const isrtl = realfont.isVisibleRightToLeft();
3471 int const dir = isrtl ? -1 : 1;
3473 frontend::CaretGeometry & cg = d->caret_geometry_;
3476 // The caret itself, slanted for italics in text edit mode except
3477 // for selections because the selection rect does not slant
3478 bool const slant = fm.italic() && cur.inTexted() && !cur.selection();
3479 double const slope = slant ? fm.italicSlope() : 0;
3480 cg.shapes.push_back(
3481 {{iround(p.x_ + dim.asc * slope), p.y_},
3482 {iround(p.x_ - dim.des * slope), p.y_ + dim.height()},
3483 {iround(p.x_ + dir * dim.wid - dim.des * slope), p.y_ + dim.height()},
3484 {iround(p.x_ + dir * dim.wid + dim.asc * slope), p.y_}}
3487 // The language indicator _| (if needed)
3488 Language const * doclang = buffer().params().language;
3489 if (!((realfont.language() == doclang && isrtl == doclang->rightToLeft())
3490 || realfont.language() == latex_language)) {
3491 int const lx = dim.height() / 3;
3492 int const xx = iround(p.x_ - dim.des * slope);
3493 int const yy = p.y_ + dim.height();
3494 cg.shapes.push_back(
3495 {{xx, yy - dim.wid},
3496 {xx + dir * (dim.wid + lx - 1), yy - dim.wid},
3497 {xx + dir * (dim.wid + lx - 1), yy},
3502 // The completion triangle |> (if needed)
3504 int const m = p.y_ + dim.height() / 2;
3505 int const d = dim.height() / 8;
3506 // offset for slanted carret
3507 int const sx = iround((dim.asc - (dim.height() / 2 - d)) * slope);
3508 // starting position x
3509 int const xx = p.x_ + dir * dim.wid + sx;
3510 cg.shapes.push_back(
3514 {xx, m + d - dim.wid},
3515 {xx + dir * d - dim.wid, m},
3516 {xx, m - d + dim.wid}}
3520 // compute extremal x values
3522 cg.right = -1000000;
3524 cg.bottom = -1000000;
3525 for (auto const & shape : cg.shapes)
3526 for (Point const & p : shape) {
3527 cg.left = min(cg.left, p.x_);
3528 cg.right = max(cg.right, p.x_);
3529 cg.top = min(cg.top, p.y_);
3530 cg.bottom = max(cg.bottom, p.y_);
3535 frontend::CaretGeometry const & BufferView::caretGeometry() const
3537 return d->caret_geometry_;
3541 bool BufferView::caretInView() const
3543 if (!paragraphVisible(cursor()))
3547 caretPosAndDim(p, dim);
3549 // does the cursor touch the screen ?
3550 if (p.y_ + dim.height() < 0 || p.y_ >= workHeight())
3556 int BufferView::horizScrollOffset() const
3558 return d->horiz_scroll_offset_;
3562 int BufferView::horizScrollOffset(Text const * text,
3563 pit_type pit, pos_type pos) const
3565 // Is this a row that is currently scrolled?
3566 if (!d->current_row_slice_.empty()
3567 && &text->inset() == d->current_row_slice_.inset().asInsetText()
3568 && pit == d->current_row_slice_.pit()
3569 && pos == d->current_row_slice_.pos())
3570 return d->horiz_scroll_offset_;
3575 void BufferView::setCurrentRowSlice(CursorSlice const & rowSlice)
3577 // nothing to do if the cursor was already on this row
3578 if (d->current_row_slice_ == rowSlice)
3581 // if the (previous) current row was scrolled, we have to
3582 // remember it in order to repaint it next time.
3583 if (d->horiz_scroll_offset_ != 0) {
3584 // search the old row in cache and mark it changed
3585 for (auto & tm_pair : d->text_metrics_) {
3586 if (&tm_pair.first->inset() == rowSlice.inset().asInsetText()) {
3587 tm_pair.second.setRowChanged(rowSlice.pit(), rowSlice.pos());
3588 // We found it, no need to continue.
3594 // Since we changed row, the scroll offset is not valid anymore
3595 d->horiz_scroll_offset_ = 0;
3596 d->current_row_slice_ = rowSlice;
3600 void BufferView::checkCursorScrollOffset()
3602 CursorSlice rowSlice = d->cursor_.bottom();
3603 TextMetrics const & tm = textMetrics(rowSlice.text());
3605 // Stop if metrics have not been computed yet, since it means
3606 // that there is nothing to do.
3607 if (!tm.contains(rowSlice.pit()))
3609 ParagraphMetrics const & pm = tm.parMetrics(rowSlice.pit());
3610 Row const & row = pm.getRow(rowSlice.pos(),
3611 d->cursor_.boundary() && rowSlice == d->cursor_.top());
3612 rowSlice.pos() = row.pos();
3614 // Set the row on which the cursor lives.
3615 setCurrentRowSlice(rowSlice);
3617 // Current x position of the cursor in pixels
3618 int cur_x = getPos(d->cursor_).x_;
3620 // Horizontal scroll offset of the cursor row in pixels
3621 int offset = d->horiz_scroll_offset_;
3622 int const MARGIN = 2 * theFontMetrics(d->cursor_.real_current_font).em()
3624 if (row.right_x() <= workWidth() - row.right_margin) {
3625 // Row is narrower than the work area, no offset needed.
3628 if (cur_x - offset < MARGIN) {
3629 // cursor would be too far right
3630 offset = cur_x - MARGIN;
3631 } else if (cur_x - offset > workWidth() - MARGIN) {
3632 // cursor would be too far left
3633 offset = cur_x - workWidth() + MARGIN;
3635 // Correct the offset to make sure that we do not scroll too much
3638 if (row.right_x() - offset < workWidth() - row.right_margin)
3639 offset = row.right_x() - workWidth() + row.right_margin;
3642 //lyxerr << "cur_x=" << cur_x << ", offset=" << offset << ", row.wid=" << row.width() << ", margin=" << MARGIN << endl;
3644 if (offset != d->horiz_scroll_offset_) {
3645 LYXERR(Debug::PAINTING, "Horiz. scroll offset changed from "
3646 << d->horiz_scroll_offset_ << " to " << offset);
3648 if (d->update_strategy_ == NoScreenUpdate)
3649 d->update_strategy_ = SingleParUpdate;
3652 d->horiz_scroll_offset_ = offset;
3656 bool BufferView::busy() const
3658 return buffer().undo().activeUndoGroup();
3662 void BufferView::draw(frontend::Painter & pain, bool paint_caret)
3666 LYXERR(Debug::PAINTING, (pain.isNull() ? "\t\t--- START NODRAW ---"
3667 : "\t\t*** START DRAWING ***"));
3668 Text & text = buffer_.text();
3669 TextMetrics const & tm = d->text_metrics_[&text];
3670 int const y = tm.first().second->position();
3671 PainterInfo pi(this, pain);
3673 // Check whether the row where the cursor lives needs to be scrolled.
3674 // Update the drawing strategy if needed.
3675 checkCursorScrollOffset();
3677 switch (d->update_strategy_) {
3679 case NoScreenUpdate:
3680 // no screen painting is actually needed. In nodraw stage
3681 // however, the different coordinates of insets and paragraphs
3682 // needs to be updated.
3683 LYXERR(Debug::PAINTING, "Strategy: NoScreenUpdate");
3684 if (pain.isNull()) {
3685 pi.full_repaint = true;
3688 pi.full_repaint = false;
3693 case SingleParUpdate:
3694 pi.full_repaint = false;
3695 LYXERR(Debug::PAINTING, "Strategy: SingleParUpdate");
3696 // In general, only the current row of the outermost paragraph
3697 // will be redrawn. Particular cases where selection spans
3698 // multiple paragraph are correctly detected in TextMetrics.
3702 case DecorationUpdate:
3703 // FIXME: We should also distinguish DecorationUpdate to avoid text
3704 // drawing if possible. This is not possible to do easily right now
3705 // because of the single backing pixmap.
3707 case FullScreenUpdate:
3709 LYXERR(Debug::PAINTING,
3710 ((d->update_strategy_ == FullScreenUpdate)
3711 ? "Strategy: FullScreenUpdate"
3712 : "Strategy: DecorationUpdate"));
3714 // The whole screen, including insets, will be refreshed.
3715 pi.full_repaint = true;
3717 // Clear background.
3718 pain.fillRectangle(0, 0, width_, height_,
3719 pi.backgroundColor(&buffer_.inset()));
3727 // Possibly grey out below
3728 if (d->update_strategy_ != NoScreenUpdate) {
3729 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3730 int const y2 = lastpm.second->bottom();
3733 Color color = buffer().isInternal()
3734 ? Color_background : Color_bottomarea;
3735 pain.fillRectangle(0, y2, width_, height_ - y2, color);
3739 LYXERR(Debug::PAINTING, (pain.isNull() ? "\t\t --- END NODRAW ---"
3740 : "\t\t *** END DRAWING ***"));
3742 // The scrollbar needs an update.
3743 // FIXME: does it always? see ticket #11947.
3744 updateScrollbarParameters();
3746 // Normalize anchor for next time (in case updateMetrics did not do it yet)
3747 // FIXME: is this useful?
3748 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
3749 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3750 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
3751 ParagraphMetrics const & pm = tm.parMetrics(pit);
3752 if (pm.bottom() > 0) {
3753 if (d->anchor_pit_ != pit
3754 || d->anchor_ypos_ != pm.position())
3755 LYXERR0(__func__ << ": Found new anchor pit = " << pit
3756 << " anchor ypos = " << pm.position()
3757 << " (was " << d->anchor_pit_ << ", " << d->anchor_ypos_ << ")"
3758 "\nIf you see this message, please report.");
3759 d->anchor_pit_ = pit;
3760 d->anchor_ypos_ = pm.position();
3765 if (!pain.isNull()) {
3766 // reset the update flags, everything has been done
3767 d->update_flags_ = Update::None;
3770 // If a caret has to be painted, mark its text row as dirty to
3771 //make sure that it will be repainted on next redraw.
3772 /* FIXME: investigate whether this can be avoided when the cursor did not
3776 Cursor cur(d->cursor_);
3777 while (cur.depth() > 1) {
3778 if (!cur.inTexted())
3780 TextMetrics const & tm = textMetrics(cur.text());
3781 if (d->caret_geometry_.left >= tm.origin().x_
3782 && d->caret_geometry_.right <= tm.origin().x_ + tm.dim().width())
3786 cur.textRow().changed(true);
3791 void BufferView::message(docstring const & msg)
3794 d->gui_->message(msg);
3798 void BufferView::showDialog(string const & name)
3801 d->gui_->showDialog(name, string());
3805 void BufferView::showDialog(string const & name,
3806 string const & data, Inset * inset)
3809 d->gui_->showDialog(name, data, inset);
3813 void BufferView::updateDialog(string const & name, string const & data)
3816 d->gui_->updateDialog(name, data);
3820 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
3826 // FIXME: Move this out of BufferView again
3827 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
3829 if (!fname.isReadableFile()) {
3830 docstring const error = from_ascii(strerror(errno));
3831 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3832 docstring const text =
3833 bformat(_("Could not read the specified document\n"
3834 "%1$s\ndue to the error: %2$s"), file, error);
3835 Alert::error(_("Could not read file"), text);
3839 if (!fname.isReadableFile()) {
3840 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3841 docstring const text =
3842 bformat(_("%1$s\n is not readable."), file);
3843 Alert::error(_("Could not open file"), text);
3847 // FIXME UNICODE: We don't know the encoding of the file
3848 docstring file_content = fname.fileContents("UTF-8");
3849 if (file_content.empty()) {
3850 Alert::error(_("Reading not UTF-8 encoded file"),
3851 _("The file is not UTF-8 encoded.\n"
3852 "It will be read as local 8Bit-encoded.\n"
3853 "If this does not give the correct result\n"
3854 "then please change the encoding of the file\n"
3855 "to UTF-8 with a program other than LyX.\n"));
3856 file_content = fname.fileContents("local8bit");
3859 return normalize_c(file_content);
3863 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
3865 docstring const tmpstr = contentsOfPlaintextFile(f);
3870 Cursor & cur = cursor();
3871 cap::replaceSelection(cur);
3872 buffer_.undo().recordUndo(cur);
3874 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
3876 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
3878 buffer_.changed(true);
3882 docstring const & BufferView::inlineCompletion() const
3884 return d->inlineCompletion_;
3888 size_t BufferView::inlineCompletionUniqueChars() const
3890 return d->inlineCompletionUniqueChars_;
3894 DocIterator const & BufferView::inlineCompletionPos() const
3896 return d->inlineCompletionPos_;
3900 void BufferView::resetInlineCompletionPos()
3902 d->inlineCompletionPos_ = DocIterator();
3906 bool samePar(DocIterator const & a, DocIterator const & b)
3908 if (a.empty() && b.empty())
3910 if (a.empty() || b.empty())
3912 if (a.depth() != b.depth())
3914 return &a.innerParagraph() == &b.innerParagraph();
3918 void BufferView::setInlineCompletion(Cursor const & cur, DocIterator const & pos,
3919 docstring const & completion, size_t uniqueChars)
3921 uniqueChars = min(completion.size(), uniqueChars);
3922 bool changed = d->inlineCompletion_ != completion
3923 || d->inlineCompletionUniqueChars_ != uniqueChars;
3924 bool singlePar = true;
3925 d->inlineCompletion_ = completion;
3926 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
3928 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
3931 DocIterator const & old = d->inlineCompletionPos_;
3933 //lyxerr << "inlineCompletionPos changed" << std::endl;
3934 // old or pos are in another paragraph?
3935 if ((!samePar(cur, pos) && !pos.empty())
3936 || (!samePar(cur, old) && !old.empty())) {
3938 //lyxerr << "different paragraph" << std::endl;
3940 d->inlineCompletionPos_ = pos;
3945 if (singlePar && !(cur.result().screenUpdate() & Update::Force))
3946 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
3948 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::Force);
3953 bool BufferView::clickableInset() const
3955 return d->clickable_inset_;
3959 bool BufferView::stats_update_trigger()
3961 if (d->stats_update_trigger_) {
3962 d->stats_update_trigger_ = false;