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 "buffer_funcs.h"
22 #include "BufferList.h"
23 #include "BufferParams.h"
24 #include "CoordCache.h"
26 #include "CutAndPaste.h"
27 #include "DispatchResult.h"
28 #include "ErrorList.h"
30 #include "FloatList.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
34 #include "InsetIterator.h"
36 #include "LaTeXFeatures.h"
37 #include "LayoutFile.h"
41 #include "LyXAction.h"
45 #include "MetricsInfo.h"
46 #include "Paragraph.h"
47 #include "ParagraphParameters.h"
48 #include "ParIterator.h"
49 #include "RowPainter.h"
52 #include "TextClass.h"
53 #include "TextMetrics.h"
55 #include "TocBackend.h"
56 #include "WordLangTuple.h"
58 #include "insets/InsetBibtex.h"
59 #include "insets/InsetCitation.h"
60 #include "insets/InsetCommand.h" // ChangeRefs
61 #include "insets/InsetExternal.h"
62 #include "insets/InsetGraphics.h"
63 #include "insets/InsetNote.h"
64 #include "insets/InsetRef.h"
65 #include "insets/InsetText.h"
67 #include "mathed/MathData.h"
68 #include "mathed/InsetMathNest.h"
70 #include "frontends/alert.h"
71 #include "frontends/Application.h"
72 #include "frontends/Delegates.h"
73 #include "frontends/FontMetrics.h"
74 #include "frontends/NullPainter.h"
75 #include "frontends/Painter.h"
76 #include "frontends/Selection.h"
78 #include "support/convert.h"
79 #include "support/debug.h"
80 #include "support/ExceptionMessage.h"
81 #include "support/filetools.h"
82 #include "support/gettext.h"
83 #include "support/lassert.h"
84 #include "support/lstrings.h"
85 #include "support/lyxlib.h"
86 #include "support/Package.h"
87 #include "support/types.h"
97 using namespace lyx::support;
101 namespace Alert = frontend::Alert;
105 /// Return an inset of this class if it exists at the current cursor position
107 T * getInsetByCode(Cursor const & cur, InsetCode code)
109 DocIterator it = cur;
110 Inset * inset = it.nextInset();
111 if (inset && inset->lyxCode() == code)
112 return static_cast<T*>(inset);
117 /// Note that comparing contents can only be used for InsetCommand
118 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
119 docstring const & contents)
121 DocIterator tmpdit = dit;
124 Inset const * inset = tmpdit.nextInset();
126 bool const valid_code = std::find(codes.begin(), codes.end(),
127 inset->lyxCode()) != codes.end();
128 InsetCommand const * ic = inset->asInsetCommand();
129 bool const same_or_no_contents = contents.empty()
130 || (ic && (ic->getFirstNonOptParam() == contents));
132 if (valid_code && same_or_no_contents) {
137 tmpdit.forwardInset();
144 /// Looks for next inset with one of the given codes.
145 /// Note that same_content can only be used for InsetCommand
146 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
150 DocIterator tmpdit = dit;
151 tmpdit.forwardInset();
155 Inset const * inset = tmpdit.nextInset();
156 if (same_content && inset) {
157 InsetCommand const * ic = inset->asInsetCommand();
159 bool const valid_code = std::find(codes.begin(), codes.end(),
160 ic->lyxCode()) != codes.end();
162 contents = ic->getFirstNonOptParam();
166 if (!findNextInset(tmpdit, codes, contents)) {
167 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
168 inset = &tmpdit.bottom().inset();
169 tmpdit = doc_iterator_begin(&inset->buffer(), inset);
170 if (!findNextInset(tmpdit, codes, contents))
182 /// Moves cursor to the next inset with one of the given codes.
183 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
186 Cursor tmpcur = bv->cursor();
187 if (!findInset(tmpcur, codes, same_content)) {
188 bv->cursor().message(_("No more insets"));
192 tmpcur.clearSelection();
193 bv->setCursor(tmpcur);
198 /// A map from a Text to the associated text metrics
199 typedef map<Text const *, TextMetrics> TextMetricsCache;
201 enum ScreenUpdateStrategy {
211 /////////////////////////////////////////////////////////////////////
215 /////////////////////////////////////////////////////////////////////
217 struct BufferView::Private
219 Private(BufferView & bv) :
220 update_strategy_(FullScreenUpdate),
221 update_flags_(Update::Force),
222 cursor_(bv), anchor_pit_(0), anchor_ypos_(0),
223 wh_(0), inlineCompletionUniqueChars_(0),
224 last_inset_(nullptr), mouse_position_cache_(),
225 gui_(nullptr), bookmark_edit_position_(-1),
226 horiz_scroll_offset_(0), clickable_inset_(false)
228 xsel_cache_.set = false;
232 ScrollbarParameters scrollbarParameters_;
234 ScreenUpdateStrategy update_strategy_;
236 Update::flags update_flags_;
238 CoordCache coord_cache_;
240 typedef map<MathData const *, MathRow> MathRows;
243 /// this is used to handle XSelection events in the right manner.
252 pit_type anchor_pit_;
255 /// Estimated average par height for scrollbar.
258 vector<int> par_height_;
261 DocIterator inlineCompletionPos_;
263 docstring inlineCompletion_;
265 size_t inlineCompletionUniqueChars_;
267 /// keyboard mapping object.
270 /// last visited inset.
271 /** kept to send setMouseHover(false).
272 * Not owned, so don't delete.
274 Inset const * last_inset_;
276 /// position of the mouse at the time of the last mouse move
277 /// This is used to update the hovering status of inset in
278 /// cases where the buffer is scrolled, but the mouse didn't move.
279 Point mouse_position_cache_;
281 mutable TextMetricsCache text_metrics_;
284 /** Not owned, so don't delete.
286 frontend::GuiBufferViewDelegate * gui_;
288 /// Cache for Find Next
289 FuncRequest search_request_cache_;
292 map<string, Inset *> edited_insets_;
294 /// When the row where the cursor lies is scrolled, this
295 /// contains the scroll offset
296 // cache for id of the paragraph which was edited the last time
297 int bookmark_edit_position_;
299 int horiz_scroll_offset_;
300 /// a slice pointing to the start of the row where the cursor
301 /// is (at last draw time)
302 CursorSlice current_row_slice_;
303 /// are we hovering something that we can click
304 bool clickable_inset_;
308 BufferView::BufferView(Buffer & buf)
309 : width_(0), height_(0), full_screen_(false), buffer_(buf),
310 d(new Private(*this))
312 d->xsel_cache_.set = false;
313 d->intl_.initKeyMapper(lyxrc.use_kbmap);
315 d->cursor_.setBuffer(&buf);
316 d->cursor_.push(buffer_.inset());
317 d->cursor_.resetAnchor();
318 d->cursor_.setCurrentFont();
320 buffer_.updatePreviews();
324 BufferView::~BufferView()
326 // current buffer is going to be switched-off, save cursor pos
327 // Ideally, the whole cursor stack should be saved, but session
328 // currently can only handle bottom (whole document) level pit and pos.
329 // That is to say, if a cursor is in a nested inset, it will be
330 // restore to the left of the top level inset.
331 LastFilePosSection::FilePos fp;
332 fp.file = buffer_.fileName();
333 fp.pit = d->cursor_.bottom().pit();
334 fp.pos = d->cursor_.bottom().pos();
335 theSession().lastFilePos().save(fp);
338 d->last_inset_->setMouseHover(this, false);
344 int BufferView::rightMargin() const
346 // The value used to be hardcoded to 10
347 int const default_margin = zoomedPixels(10);
348 // The additional test for the case the outliner is opened.
349 if (!full_screen_ || !lyxrc.full_screen_limit
350 || width_ < lyxrc.full_screen_width + 2 * default_margin)
351 return default_margin;
353 return (width_ - lyxrc.full_screen_width) / 2;
357 int BufferView::leftMargin() const
359 return rightMargin();
363 int BufferView::inPixels(Length const & len) const
365 Font const font = buffer().params().getFont();
366 return len.inPixels(workWidth(), theFontMetrics(font).em());
370 int BufferView::zoomedPixels(int pix) const
372 // FIXME: the dpi setting should really depend on the BufferView
373 // (think different monitors).
375 // Zoom factor specified by user in percent
376 double const zoom = lyxrc.currentZoom / 100.0; // [percent]
378 // DPI setting for monitor relative to 100dpi
379 double const dpizoom = lyxrc.dpi / 100.0; // [per 100dpi]
381 return support::iround(pix * zoom * dpizoom);
385 bool BufferView::isTopScreen() const
387 return 0 == d->scrollbarParameters_.min;
391 bool BufferView::isBottomScreen() const
393 return 0 == d->scrollbarParameters_.max;
397 Intl & BufferView::getIntl()
403 Intl const & BufferView::getIntl() const
409 CoordCache & BufferView::coordCache()
411 return d->coord_cache_;
415 CoordCache const & BufferView::coordCache() const
417 return d->coord_cache_;
421 MathRow const & BufferView::mathRow(MathData const * cell) const
423 auto it = d->math_rows_.find(cell);
424 LATTEST(it != d->math_rows_.end());
429 void BufferView::setMathRow(MathData const * cell, MathRow const & mrow)
431 d->math_rows_[cell] = mrow;
435 Buffer & BufferView::buffer()
441 Buffer const & BufferView::buffer() const
447 bool BufferView::needsFitCursor() const
449 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
450 frontend::FontMetrics const & fm =
451 theFontMetrics(d->cursor_.getFont().fontInfo());
452 int const asc = fm.maxAscent();
453 int const des = fm.maxDescent();
454 Point const p = getPos(d->cursor_);
455 if (p.y_ - asc >= 0 && p.y_ + des < height_)
464 // this is for debugging only.
465 string flagsAsString(Update::flags flags)
467 if (flags == Update::None)
469 return string((flags & Update::FitCursor) ? "FitCursor " : "")
470 + ((flags & Update::Force) ? "Force " : "")
471 + ((flags & Update::ForceDraw) ? "ForceDraw " : "")
472 + ((flags & Update::SinglePar) ? "SinglePar " : "")
473 + ((flags & Update::Decoration) ? "Decoration " : "");
478 void BufferView::processUpdateFlags(Update::flags flags)
480 LYXERR(Debug::PAINTING, "BufferView::processUpdateFlags( "
481 << flagsAsString(flags) << ") buffer: " << &buffer_);
483 // Case when no explicit update is requested.
484 if (flags == Update::None)
487 /* FIXME We would like to avoid doing this here, since it is very
488 * expensive and is called in updateBuffer already. However, even
489 * inserting a plain character can invalidate the overly fragile
490 * tables of child documents built by updateMacros. Some work is
491 * needed to avoid doing that when not necessary.
493 buffer_.updateMacros();
495 // First check whether the metrics and inset positions should be updated
496 if (flags & Update::Force) {
497 // This will update the CoordCache items and replace Force
498 // with ForceDraw in flags.
499 updateMetrics(flags);
502 // Detect whether we can only repaint a single paragraph (if we
503 // are not already redrawing all).
504 // We handle this before FitCursor because the later will require
505 // correct metrics at cursor position.
506 if (!(flags & Update::ForceDraw)
507 && (flags & Update::SinglePar)
508 && !singleParUpdate())
509 updateMetrics(flags);
511 // Then make sure that the screen contains the cursor if needed
512 if (flags & Update::FitCursor) {
513 if (needsFitCursor()) {
514 // First try to make the selection start visible
515 // (which is just the cursor when there is no selection)
516 scrollToCursor(d->cursor_.selectionBegin(), false);
517 // Metrics have to be recomputed (maybe again)
519 // Is the cursor visible? (only useful if cursor is at end of selection)
520 if (needsFitCursor()) {
521 // then try to make cursor visible instead
522 scrollToCursor(d->cursor_, false);
523 // Metrics have to be recomputed (maybe again)
524 updateMetrics(flags);
527 flags = flags & ~Update::FitCursor;
530 // Add flags to the the update flags. These will be reset to None
531 // after the redraw is actually done
532 d->update_flags_ = d->update_flags_ | flags;
533 LYXERR(Debug::PAINTING, "Cumulative flags: " << flagsAsString(flags));
535 // Now compute the update strategy
536 // Possibly values in flag are None, SinglePar, Decoration, ForceDraw
537 LATTEST((d->update_flags_ & ~(Update::None | Update::SinglePar
538 | Update::Decoration | Update::ForceDraw)) == 0);
540 if (d->update_flags_ & Update::ForceDraw)
541 d->update_strategy_ = FullScreenUpdate;
542 else if (d->update_flags_ & Update::Decoration)
543 d->update_strategy_ = DecorationUpdate;
544 else if (d->update_flags_ & Update::SinglePar)
545 d->update_strategy_ = SingleParUpdate;
547 // no need to redraw anything.
548 d->update_strategy_ = NoScreenUpdate;
551 updateHoveredInset();
554 buffer_.changed(false);
558 void BufferView::updateScrollbar()
560 if (height_ == 0 && width_ == 0)
563 // We prefer fixed size line scrolling.
564 d->scrollbarParameters_.single_step = defaultRowHeight();
565 // We prefer full screen page scrolling.
566 d->scrollbarParameters_.page_step = height_;
568 Text & t = buffer_.text();
569 TextMetrics & tm = d->text_metrics_[&t];
571 LYXERR(Debug::GUI, " Updating scrollbar: height: "
572 << t.paragraphs().size()
573 << " curr par: " << d->cursor_.bottom().pit()
574 << " default height " << defaultRowHeight());
576 size_t const parsize = t.paragraphs().size();
577 if (d->par_height_.size() != parsize) {
578 d->par_height_.clear();
579 // FIXME: We assume a default paragraph height of 2 rows. This
580 // should probably be pondered with the screen width.
581 d->par_height_.resize(parsize, defaultRowHeight() * 2);
584 // Look at paragraph heights on-screen
585 pair<pit_type, ParagraphMetrics const *> first = tm.first();
586 pair<pit_type, ParagraphMetrics const *> last = tm.last();
587 for (pit_type pit = first.first; pit <= last.first; ++pit) {
588 d->par_height_[pit] = tm.parMetrics(pit).height();
589 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
590 << d->par_height_[pit]);
593 int top_pos = first.second->position() - first.second->ascent();
594 int bottom_pos = last.second->position() + last.second->descent();
595 bool first_visible = first.first == 0 && top_pos >= 0;
596 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
597 if (first_visible && last_visible) {
598 d->scrollbarParameters_.min = 0;
599 d->scrollbarParameters_.max = 0;
603 d->scrollbarParameters_.min = top_pos;
604 for (size_t i = 0; i != size_t(first.first); ++i)
605 d->scrollbarParameters_.min -= d->par_height_[i];
606 d->scrollbarParameters_.max = bottom_pos;
607 for (size_t i = last.first + 1; i != parsize; ++i)
608 d->scrollbarParameters_.max += d->par_height_[i];
610 // The reference is the top position so we remove one page.
611 if (lyxrc.scroll_below_document)
612 d->scrollbarParameters_.max -= minVisiblePart();
614 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
616 // 0 must be inside the range as it denotes the current position
617 if (d->scrollbarParameters_.max < 0)
618 d->scrollbarParameters_.max = 0;
619 if (d->scrollbarParameters_.min > 0)
620 d->scrollbarParameters_.min = 0;
624 ScrollbarParameters const & BufferView::scrollbarParameters() const
626 return d->scrollbarParameters_;
630 docstring BufferView::toolTip(int x, int y) const
632 // Get inset under mouse, if there is one.
633 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
635 // No inset, no tooltip...
637 return covering_inset->toolTip(*this, x, y);
641 string BufferView::contextMenu(int x, int y) const
643 //If there is a selection, return the containing inset menu
644 if (d->cursor_.selection())
645 return d->cursor_.inset().contextMenu(*this, x, y);
647 // Get inset under mouse, if there is one.
648 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
650 return covering_inset->contextMenu(*this, x, y);
652 return buffer_.inset().contextMenu(*this, x, y);
657 void BufferView::scrollDocView(int const value, bool update)
659 // The scrollbar values are relative to the top of the screen, therefore the
660 // offset is equal to the target value.
662 // No scrolling at all? No need to redraw anything
666 // If the offset is less than 2 screen height, prefer to scroll instead.
667 if (abs(value) <= 2 * height_) {
668 d->anchor_ypos_ -= value;
669 processUpdateFlags(Update::Force);
673 // cut off at the top
674 if (value <= d->scrollbarParameters_.min) {
675 DocIterator dit = doc_iterator_begin(&buffer_);
676 showCursor(dit, false, update);
677 LYXERR(Debug::SCROLLING, "scroll to top");
681 // cut off at the bottom
682 if (value >= d->scrollbarParameters_.max) {
683 DocIterator dit = doc_iterator_end(&buffer_);
685 showCursor(dit, false, update);
686 LYXERR(Debug::SCROLLING, "scroll to bottom");
690 // find paragraph at target position
691 int par_pos = d->scrollbarParameters_.min;
693 for (; i != int(d->par_height_.size()); ++i) {
694 par_pos += d->par_height_[i];
695 if (par_pos >= value)
699 if (par_pos < value) {
700 // It seems we didn't find the correct pit so stay on the safe side and
702 LYXERR0("scrolling position not found!");
703 scrollDocView(d->scrollbarParameters_.max, update);
707 DocIterator dit = doc_iterator_begin(&buffer_);
709 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
710 showCursor(dit, false, update);
714 // FIXME: this method is not working well.
715 void BufferView::setCursorFromScrollbar()
717 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
719 int const height = 2 * defaultRowHeight();
720 int const first = height;
721 int const last = height_ - height;
723 Cursor const & oldcur = d->cursor_;
725 switch (cursorStatus(oldcur)) {
733 int const y = getPos(oldcur).y_;
734 newy = min(last, max(y, first));
738 // We reset the cursor because cursorStatus() does not
739 // work when the cursor is within mathed.
742 tm.setCursorFromCoordinates(cur, 0, newy);
744 // update the bufferview cursor and notify insets
745 // FIXME: Care about the d->cursor_ flags to redraw if needed
746 Cursor old = d->cursor_;
748 // the DEPM call in mouseSetCursor() might have destroyed the
749 // paragraph the cursor is in.
750 bool badcursor = old.fixIfBroken();
751 badcursor |= notifyCursorLeavesOrEnters(old, d->cursor_);
753 d->cursor_.fixIfBroken();
757 Change const BufferView::getCurrentChange() const
759 if (!d->cursor_.selection())
760 return Change(Change::UNCHANGED);
762 DocIterator dit = d->cursor_.selectionBegin();
763 // The selected content might have been changed (see #7685)
764 dit = dit.getInnerText();
765 return dit.paragraph().lookupChange(dit.pos());
769 // this could be used elsewhere as well?
770 // FIXME: This does not work within mathed!
771 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
773 Point const p = getPos(dit);
776 if (p.y_ > workHeight())
782 void BufferView::bookmarkEditPosition()
784 // Don't eat cpu time for each keystroke
785 if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
788 d->bookmark_edit_position_ = d->cursor_.paragraph().id();
792 void BufferView::saveBookmark(unsigned int idx)
794 // tentatively save bookmark, id and pos will be used to
795 // acturately locate a bookmark in a 'live' lyx session.
796 // pit and pos will be updated with bottom level pit/pos
798 if (!buffer_.isInternal()) {
799 theSession().bookmarks().save(
801 d->cursor_.bottom().pit(),
802 d->cursor_.bottom().pos(),
803 d->cursor_.paragraph().id(),
808 // emit message signal.
809 message(_("Save bookmark"));
814 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
815 int top_id, pos_type top_pos)
817 bool success = false;
820 d->cursor_.clearSelection();
822 // if a valid par_id is given, try it first
823 // This is the case for a 'live' bookmark when unique paragraph ID
824 // is used to track bookmarks.
826 dit = buffer_.getParFromID(top_id);
828 dit.pos() = min(dit.paragraph().size(), top_pos);
829 // Some slices of the iterator may not be
830 // reachable (e.g. closed collapsible inset)
831 // so the dociterator may need to be
832 // shortened. Otherwise, setCursor may crash
833 // lyx when the cursor can not be set to these
835 size_t const n = dit.depth();
836 for (size_t i = 0; i < n; ++i)
837 if (!dit[i].inset().editable()) {
845 // if top_id == 0, or searching through top_id failed
846 // This is the case for a 'restored' bookmark when only bottom
847 // (document level) pit was saved. Because of this, bookmark
848 // restoration is inaccurate. If a bookmark was within an inset,
849 // it will be restored to the left of the outmost inset that contains
851 if (bottom_pit < int(buffer_.paragraphs().size())) {
852 dit = doc_iterator_begin(&buffer_);
854 dit.pit() = bottom_pit;
855 dit.pos() = min(bottom_pos, dit.paragraph().size());
860 // Note: only bottom (document) level pit is set.
862 // set the current font.
863 d->cursor_.setCurrentFont();
864 // Do not forget to reset the anchor (see #9912)
865 d->cursor_.resetAnchor();
866 processUpdateFlags(Update::Force | Update::FitCursor);
873 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
875 if (d->cursor_.real_current_font.isRightToLeft()) {
876 if (d->intl_.keymap == Intl::PRIMARY)
877 d->intl_.keyMapSec();
879 if (d->intl_.keymap == Intl::SECONDARY)
880 d->intl_.keyMapPrim();
883 d->intl_.getTransManager().translateAndInsert(c, t, cur);
887 int BufferView::workWidth() const
893 void BufferView::recenter()
895 showCursor(d->cursor_, true, true);
899 void BufferView::showCursor()
901 showCursor(d->cursor_, false, true);
905 void BufferView::showCursor(DocIterator const & dit,
906 bool recenter, bool update)
908 if (scrollToCursor(dit, recenter) && update)
909 processUpdateFlags(Update::Force);
913 void BufferView::scrollToCursor()
915 if (scrollToCursor(d->cursor_, false))
916 processUpdateFlags(Update::Force);
920 bool BufferView::scrollToCursor(DocIterator const & dit, bool const recenter)
922 // We are not properly started yet, delay until resizing is
928 LYXERR(Debug::SCROLLING, "recentering and scrolling to cursor");
930 LYXERR(Debug::SCROLLING, "scrolling to cursor");
932 CursorSlice const & bot = dit.bottom();
933 TextMetrics & tm = d->text_metrics_[bot.text()];
935 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
936 int bot_pit = bot.pit();
937 if (bot_pit > max_pit) {
938 // FIXME: Why does this happen?
939 LYXERR0("bottom pit is greater that max pit: "
940 << bot_pit << " > " << max_pit);
944 if (bot_pit == tm.first().first - 1)
945 tm.newParMetricsUp();
946 else if (bot_pit == tm.last().first + 1)
947 tm.newParMetricsDown();
949 if (tm.contains(bot_pit)) {
950 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
951 LBUFERR(!pm.rows().empty());
952 // FIXME: smooth scrolling doesn't work in mathed.
953 CursorSlice const & cs = dit.innerTextSlice();
954 int offset = coordOffset(dit).y_;
955 int ypos = pm.position() + offset;
956 Dimension const & row_dim =
957 pm.getRow(cs.pos(), dit.boundary()).dim();
960 scrolled = scroll(ypos - height_/2);
962 // We try to visualize the whole row, if the row height is larger than
963 // the screen height, we scroll to a heuristic value of height_ / 4.
964 // FIXME: This heuristic value should be replaced by a recursive search
965 // for a row in the inset that can be visualized completely.
966 else if (row_dim.height() > height_) {
967 if (ypos < defaultRowHeight())
968 scrolled = scroll(ypos - height_ / 4);
969 else if (ypos > height_ - defaultRowHeight())
970 scrolled = scroll(ypos - 3 * height_ / 4);
973 // If the top part of the row falls of the screen, we scroll
974 // up to align the top of the row with the top of the screen.
975 else if (ypos - row_dim.ascent() < 0 && ypos < height_) {
976 int ynew = row_dim.ascent();
977 scrolled = scrollUp(ynew - ypos);
980 // If the bottom of the row falls of the screen, we scroll down.
981 else if (ypos + row_dim.descent() > height_ && ypos > 0) {
982 int ynew = height_ - row_dim.descent();
983 scrolled = scrollDown(ypos - ynew);
986 // else, nothing to do, the cursor is already visible so we just return.
987 return scrolled != 0;
990 // fix inline completion position
991 if (d->inlineCompletionPos_.fixIfBroken())
992 d->inlineCompletionPos_ = DocIterator();
994 tm.redoParagraph(bot_pit);
995 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
996 int offset = coordOffset(dit).y_;
998 d->anchor_pit_ = bot_pit;
999 CursorSlice const & cs = dit.innerTextSlice();
1000 Dimension const & row_dim =
1001 pm.getRow(cs.pos(), dit.boundary()).dim();
1004 d->anchor_ypos_ = height_/2;
1005 else if (d->anchor_pit_ == 0)
1006 d->anchor_ypos_ = offset + pm.ascent();
1007 else if (d->anchor_pit_ == max_pit)
1008 d->anchor_ypos_ = height_ - offset - row_dim.descent();
1009 else if (offset > height_)
1010 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
1012 d->anchor_ypos_ = defaultRowHeight() * 2;
1018 void BufferView::makeDocumentClass()
1020 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
1021 buffer_.params().makeDocumentClass();
1022 updateDocumentClass(olddc);
1026 void BufferView::updateDocumentClass(DocumentClassConstPtr olddc)
1028 message(_("Converting document to new document class..."));
1030 StableDocIterator backcur(d->cursor_);
1031 ErrorList & el = buffer_.errorList("Class Switch");
1032 cap::switchBetweenClasses(
1033 olddc, buffer_.params().documentClassPtr(),
1034 static_cast<InsetText &>(buffer_.inset()), el);
1036 setCursor(backcur.asDocIterator(&buffer_));
1038 buffer_.errors("Class Switch");
1042 /** Return the change status at cursor position, taking into account the
1043 * status at each level of the document iterator (a table in a deleted
1044 * footnote is deleted).
1045 * When \param outer is true, the top slice is not looked at.
1047 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
1049 size_t const depth = dit.depth() - (outer ? 1 : 0);
1051 for (size_t i = 0 ; i < depth ; ++i) {
1052 CursorSlice const & slice = dit[i];
1053 if (!slice.inset().inMathed()
1054 && slice.pos() < slice.paragraph().size()) {
1055 Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
1056 if (ch != Change::UNCHANGED)
1060 return Change::UNCHANGED;
1064 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1066 FuncCode const act = cmd.action();
1068 // Can we use a readonly buffer?
1069 if (buffer_.isReadonly()
1070 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1071 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1072 if (buffer_.hasReadonlyFlag())
1073 flag.message(from_utf8(N_("Document is read-only")));
1075 flag.message(from_utf8(N_("Document has been modified externally")));
1076 flag.setEnabled(false);
1080 // Are we in a DELETED change-tracking region?
1081 if (lookupChangeType(d->cursor_, true) == Change::DELETED
1082 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1083 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1084 flag.message(from_utf8(N_("This portion of the document is deleted.")));
1085 flag.setEnabled(false);
1089 Cursor & cur = d->cursor_;
1091 if (cur.getStatus(cmd, flag))
1096 // FIXME: This is a bit problematic because we don't check if this is
1097 // a document BufferView or not for these LFUNs. We probably have to
1098 // dispatch both to currentBufferView() and, if that fails,
1099 // to documentBufferView(); same as we do now for current Buffer and
1100 // document Buffer. Ideally those LFUN should go to Buffer as they
1101 // operate on the full Buffer and the cursor is only needed either for
1102 // an Undo record or to restore a cursor position. But we don't know
1103 // how to do that inside Buffer of course.
1104 case LFUN_BUFFER_PARAMS_APPLY:
1105 case LFUN_LAYOUT_MODULES_CLEAR:
1106 case LFUN_LAYOUT_MODULE_ADD:
1107 case LFUN_LAYOUT_RELOAD:
1108 case LFUN_TEXTCLASS_APPLY:
1109 case LFUN_TEXTCLASS_LOAD:
1110 flag.setEnabled(!buffer_.isReadonly());
1114 // We do not use the LyXAction flag for readonly because Undo sets the
1115 // buffer clean/dirty status by itself.
1116 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasUndoStack());
1119 // We do not use the LyXAction flag for readonly because Redo sets the
1120 // buffer clean/dirty status by itself.
1121 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasRedoStack());
1123 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1124 case LFUN_FILE_INSERT_PLAINTEXT: {
1125 docstring const fname = cmd.argument();
1126 if (!FileName::isAbsolute(to_utf8(fname))) {
1127 flag.message(_("Absolute filename expected."));
1130 flag.setEnabled(cur.inTexted());
1133 case LFUN_FILE_INSERT:
1134 case LFUN_BOOKMARK_SAVE:
1135 // FIXME: Actually, these LFUNS should be moved to Text
1136 flag.setEnabled(cur.inTexted());
1139 case LFUN_FONT_STATE:
1140 case LFUN_LABEL_INSERT:
1141 case LFUN_INFO_INSERT:
1142 case LFUN_PARAGRAPH_GOTO:
1143 case LFUN_NOTE_NEXT:
1144 case LFUN_REFERENCE_NEXT:
1145 case LFUN_WORD_FIND:
1146 case LFUN_WORD_FIND_FORWARD:
1147 case LFUN_WORD_FIND_BACKWARD:
1148 case LFUN_WORD_REPLACE:
1151 case LFUN_MARK_TOGGLE:
1152 case LFUN_SCREEN_RECENTER:
1153 case LFUN_SCREEN_SHOW_CURSOR:
1154 case LFUN_BIBTEX_DATABASE_ADD:
1155 case LFUN_BIBTEX_DATABASE_DEL:
1156 case LFUN_STATISTICS:
1157 case LFUN_KEYMAP_OFF:
1158 case LFUN_KEYMAP_PRIMARY:
1159 case LFUN_KEYMAP_SECONDARY:
1160 case LFUN_KEYMAP_TOGGLE:
1161 case LFUN_INSET_SELECT_ALL:
1162 flag.setEnabled(true);
1165 case LFUN_GRAPHICS_UNIFY:
1166 flag.setEnabled(cur.countInsetsInSelection(GRAPHICS_CODE)>1);
1169 case LFUN_WORD_FINDADV: {
1170 FindAndReplaceOptions opt;
1171 istringstream iss(to_utf8(cmd.argument()));
1173 flag.setEnabled(opt.repl_buf_name.empty()
1174 || !buffer_.isReadonly());
1178 case LFUN_LABEL_GOTO:
1179 flag.setEnabled(!cmd.argument().empty()
1180 || getInsetByCode<InsetRef>(cur, REF_CODE));
1183 case LFUN_CHANGES_MERGE:
1184 case LFUN_CHANGE_NEXT:
1185 case LFUN_CHANGE_PREVIOUS:
1186 case LFUN_ALL_CHANGES_ACCEPT:
1187 case LFUN_ALL_CHANGES_REJECT:
1188 flag.setEnabled(buffer_.areChangesPresent());
1191 case LFUN_SCREEN_UP:
1192 case LFUN_SCREEN_DOWN:
1194 case LFUN_SCREEN_UP_SELECT:
1195 case LFUN_SCREEN_DOWN_SELECT:
1196 case LFUN_INSET_FORALL:
1197 flag.setEnabled(true);
1200 case LFUN_LAYOUT_TABULAR:
1201 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1205 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1208 case LFUN_LAYOUT_PARAGRAPH:
1209 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1212 case LFUN_BRANCH_ADD_INSERT:
1213 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1216 case LFUN_DIALOG_SHOW_NEW_INSET:
1217 // FIXME: this is wrong, but I do not understand the
1219 if (cur.inset().lyxCode() == CAPTION_CODE)
1220 return cur.inset().getStatus(cur, cmd, flag);
1221 // FIXME we should consider passthru paragraphs too.
1222 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1225 case LFUN_CITATION_INSERT: {
1226 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1227 // FIXME: This could turn in a recursive hell.
1228 // Shouldn't we use Buffer::getStatus() instead?
1229 flag.setEnabled(lyx::getStatus(fr).enabled());
1232 case LFUN_INSET_APPLY: {
1233 string const name = cmd.getArg(0);
1234 Inset * inset = editedInset(name);
1236 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1237 if (!inset->getStatus(cur, fr, flag)) {
1238 // Every inset is supposed to handle this
1239 LASSERT(false, break);
1242 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1243 flag = lyx::getStatus(fr);
1256 Inset * BufferView::editedInset(string const & name) const
1258 map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1259 return it == d->edited_insets_.end() ? nullptr : it->second;
1263 void BufferView::editInset(string const & name, Inset * inset)
1266 d->edited_insets_[name] = inset;
1268 d->edited_insets_.erase(name);
1272 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1274 LYXERR(Debug::ACTION, "BufferView::dispatch: cmd: " << cmd);
1276 string const argument = to_utf8(cmd.argument());
1277 Cursor & cur = d->cursor_;
1280 // Don't dispatch function that does not apply to internal buffers.
1281 if (buffer_.isInternal()
1282 && lyxaction.funcHasFlag(cmd.action(), LyXAction::NoInternal))
1285 // We'll set this back to false if need be.
1286 bool dispatched = true;
1287 buffer_.undo().beginUndoGroup();
1289 FuncCode const act = cmd.action();
1292 case LFUN_BUFFER_PARAMS_APPLY: {
1293 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
1294 cur.recordUndoBufferParams();
1295 istringstream ss(to_utf8(cmd.argument()));
1298 int const unknown_tokens = buffer_.readHeader(lex);
1299 if (unknown_tokens != 0) {
1300 LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1301 << unknown_tokens << " unknown token"
1302 << (unknown_tokens == 1 ? "" : "s"));
1304 updateDocumentClass(olddc);
1306 // We are most certainly here because of a change in the document
1307 // It is then better to make sure that all dialogs are in sync with
1308 // current document settings.
1309 dr.screenUpdate(Update::Force | Update::FitCursor);
1310 dr.forceBufferUpdate();
1314 case LFUN_LAYOUT_MODULES_CLEAR: {
1315 // FIXME: this modifies the document in cap::switchBetweenClasses
1316 // without calling recordUndo. Fix this before using
1317 // recordUndoBufferParams().
1318 cur.recordUndoFullBuffer();
1319 buffer_.params().clearLayoutModules();
1320 makeDocumentClass();
1321 dr.screenUpdate(Update::Force);
1322 dr.forceBufferUpdate();
1326 case LFUN_LAYOUT_MODULE_ADD: {
1327 BufferParams const & params = buffer_.params();
1328 if (!params.layoutModuleCanBeAdded(argument)) {
1329 LYXERR0("Module `" << argument <<
1330 "' cannot be added due to failed requirements or "
1331 "conflicts with installed modules.");
1334 // FIXME: this modifies the document in cap::switchBetweenClasses
1335 // without calling recordUndo. Fix this before using
1336 // recordUndoBufferParams().
1337 cur.recordUndoFullBuffer();
1338 buffer_.params().addLayoutModule(argument);
1339 makeDocumentClass();
1340 dr.screenUpdate(Update::Force);
1341 dr.forceBufferUpdate();
1345 case LFUN_TEXTCLASS_APPLY: {
1346 // since this shortcircuits, the second call is made only if
1348 bool const success =
1349 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1350 LayoutFileList::get().load(argument, buffer_.filePath());
1352 docstring s = bformat(_("The document class `%1$s' "
1353 "could not be loaded."), from_utf8(argument));
1354 frontend::Alert::error(_("Could not load class"), s);
1358 LayoutFile const * old_layout = buffer_.params().baseClass();
1359 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1361 if (old_layout == new_layout)
1365 // Save the old, possibly modular, layout for use in conversion.
1366 // FIXME: this modifies the document in cap::switchBetweenClasses
1367 // without calling recordUndo. Fix this before using
1368 // recordUndoBufferParams().
1369 cur.recordUndoFullBuffer();
1370 buffer_.params().setBaseClass(argument, buffer_.layoutPos());
1371 makeDocumentClass();
1372 dr.screenUpdate(Update::Force);
1373 dr.forceBufferUpdate();
1377 case LFUN_TEXTCLASS_LOAD: {
1378 // since this shortcircuits, the second call is made only if
1380 bool const success =
1381 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1382 LayoutFileList::get().load(argument, buffer_.filePath());
1384 docstring s = bformat(_("The document class `%1$s' "
1385 "could not be loaded."), from_utf8(argument));
1386 frontend::Alert::error(_("Could not load class"), s);
1391 case LFUN_LAYOUT_RELOAD: {
1392 LayoutFileIndex bc = buffer_.params().baseClassID();
1393 LayoutFileList::get().reset(bc);
1394 buffer_.params().setBaseClass(bc, buffer_.layoutPos());
1395 makeDocumentClass();
1396 dr.screenUpdate(Update::Force);
1397 dr.forceBufferUpdate();
1402 dr.setMessage(_("Undo"));
1403 cur.clearSelection();
1404 // We need to find out if the bibliography information
1405 // has changed. See bug #11055.
1406 // So these should not be references...
1407 string const engine = buffer().params().citeEngine();
1408 CiteEngineType const enginetype = buffer().params().citeEngineType();
1409 if (!cur.undoAction())
1410 dr.setMessage(_("No further undo information"));
1412 dr.screenUpdate(Update::Force | Update::FitCursor);
1413 dr.forceBufferUpdate();
1414 if (buffer().params().citeEngine() != engine ||
1415 buffer().params().citeEngineType() != enginetype)
1416 buffer().invalidateCiteLabels();
1422 dr.setMessage(_("Redo"));
1423 cur.clearSelection();
1424 // We need to find out if the bibliography information
1425 // has changed. See bug #11055.
1426 // So these should not be references...
1427 string const engine = buffer().params().citeEngine();
1428 CiteEngineType const enginetype = buffer().params().citeEngineType();
1429 if (!cur.redoAction())
1430 dr.setMessage(_("No further redo information"));
1432 dr.screenUpdate(Update::Force | Update::FitCursor);
1433 dr.forceBufferUpdate();
1434 if (buffer().params().citeEngine() != engine ||
1435 buffer().params().citeEngineType() != enginetype)
1436 buffer().invalidateCiteLabels();
1441 case LFUN_FONT_STATE:
1442 dr.setMessage(cur.currentState(false));
1445 case LFUN_BOOKMARK_SAVE:
1446 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1449 case LFUN_LABEL_GOTO: {
1450 docstring label = cmd.argument();
1451 if (label.empty()) {
1453 getInsetByCode<InsetRef>(cur, REF_CODE);
1455 label = inset->getParam("reference");
1456 // persistent=false: use temp_bookmark
1460 if (!label.empty()) {
1462 // at the moment, this is redundant, since gotoLabel will
1463 // eventually call LFUN_PARAGRAPH_GOTO, but it seems best
1465 dr.screenUpdate(Update::Force | Update::FitCursor);
1470 case LFUN_PARAGRAPH_GOTO: {
1471 int const id = convert<int>(cmd.getArg(0));
1472 pos_type const pos = convert<int>(cmd.getArg(1));
1475 string const str_id_end = cmd.getArg(2);
1476 string const str_pos_end = cmd.getArg(3);
1478 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1479 b = theBufferList().next(b)) {
1482 curs.setCursor(b->getParFromID(id));
1484 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1488 LYXERR(Debug::INFO, "Paragraph " << curs.paragraph().id()
1489 << " found in buffer `"
1490 << b->absFileName() << "'.");
1492 if (b == &buffer_) {
1494 if (str_id_end.empty() || str_pos_end.empty()) {
1497 mouseSetCursor(curs);
1500 int const id_end = convert<int>(str_id_end);
1501 pos_type const pos_end = convert<int>(str_pos_end);
1502 success = setCursorFromEntries({id, pos},
1506 dr.screenUpdate(Update::Force | Update::FitCursor);
1508 // Switch to other buffer view and resend cmd
1509 lyx::dispatch(FuncRequest(
1510 LFUN_BUFFER_SWITCH, b->absFileName()));
1518 case LFUN_NOTE_NEXT:
1519 gotoInset(this, { NOTE_CODE }, false);
1520 // FIXME: if SinglePar is changed to act on the inner
1521 // paragraph, this will not be OK anymore. The update is
1522 // useful for auto-open collapsible insets.
1523 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1526 case LFUN_REFERENCE_NEXT: {
1527 gotoInset(this, { LABEL_CODE, REF_CODE }, true);
1528 // FIXME: if SinglePar is changed to act on the inner
1529 // paragraph, this will not be OK anymore. The update is
1530 // useful for auto-open collapsible insets.
1531 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1535 case LFUN_CHANGE_NEXT:
1536 findNextChange(this);
1537 if (cur.inset().isTable())
1538 // In tables, there might be whole changed rows or columns
1540 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1541 dr.screenUpdate(Update::Force | Update::FitCursor);
1544 case LFUN_CHANGE_PREVIOUS:
1545 findPreviousChange(this);
1546 if (cur.inset().isTable())
1547 // In tables, there might be whole changed rows or columns
1549 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1550 dr.screenUpdate(Update::Force | Update::FitCursor);
1553 case LFUN_CHANGES_MERGE:
1554 if (findNextChange(this) || findPreviousChange(this)) {
1555 dr.screenUpdate(Update::Force | Update::FitCursor);
1556 dr.forceBufferUpdate();
1557 showDialog("changes");
1561 case LFUN_ALL_CHANGES_ACCEPT: {
1562 // select complete document
1564 cur.selHandle(true);
1565 buffer_.text().cursorBottom(cur);
1566 // accept everything in a single step to support atomic undo
1567 // temporarily disable track changes in order to end with really
1568 // no new (e.g., DPSM-caused) changes (see #7487)
1569 bool const track = buffer_.params().track_changes;
1570 buffer_.params().track_changes = false;
1571 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1572 buffer_.params().track_changes = track;
1574 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1575 dr.screenUpdate(Update::Force | Update::FitCursor);
1576 dr.forceBufferUpdate();
1580 case LFUN_ALL_CHANGES_REJECT: {
1581 // select complete document
1583 cur.selHandle(true);
1584 buffer_.text().cursorBottom(cur);
1585 // reject everything in a single step to support atomic undo
1586 // temporarily disable track changes in order to end with really
1587 // no new (e.g., DPSM-caused) changes (see #7487)
1588 bool const track = buffer_.params().track_changes;
1589 buffer_.params().track_changes = false;
1590 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1591 buffer_.params().track_changes = track;
1593 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1594 dr.screenUpdate(Update::Force | Update::FitCursor);
1595 dr.forceBufferUpdate();
1599 case LFUN_WORD_FIND_FORWARD:
1600 case LFUN_WORD_FIND_BACKWARD: {
1602 // Would it maybe be better if this variable were view specific anyway?
1603 static docstring last_search;
1604 docstring searched_string;
1606 if (!cmd.argument().empty()) {
1607 last_search = cmd.argument();
1608 searched_string = cmd.argument();
1610 searched_string = last_search;
1613 if (searched_string.empty())
1616 bool const fw = act == LFUN_WORD_FIND_FORWARD;
1617 docstring const data =
1618 find2string(searched_string, true, false, fw);
1619 bool found = lyxfind(this, FuncRequest(LFUN_WORD_FIND, data));
1621 dr.screenUpdate(Update::Force | Update::FitCursor);
1625 case LFUN_WORD_FIND: {
1626 FuncRequest req = cmd;
1627 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1628 req = d->search_request_cache_;
1629 if (req.argument().empty()) {
1630 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1633 if (lyxfind(this, req))
1634 dr.screenUpdate(Update::Force | Update::FitCursor);
1636 d->search_request_cache_ = req;
1640 case LFUN_WORD_REPLACE: {
1641 bool has_deleted = false;
1642 if (cur.selection()) {
1643 DocIterator beg = cur.selectionBegin();
1644 DocIterator end = cur.selectionEnd();
1645 if (beg.pit() == end.pit()) {
1646 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1647 if (!cur.inMathed() && cur.paragraph().isDeleted(p)) {
1654 if (lyxreplace(this, cmd, has_deleted)) {
1655 dr.forceBufferUpdate();
1656 dr.screenUpdate(Update::Force | Update::FitCursor);
1661 case LFUN_WORD_FINDADV: {
1662 FindAndReplaceOptions opt;
1663 istringstream iss(to_utf8(cmd.argument()));
1665 if (findAdv(this, opt)) {
1666 dr.screenUpdate(Update::Force | Update::FitCursor);
1677 cur.clearSelection();
1678 dr.setMessage(from_utf8(N_("Mark off")));
1682 cur.clearSelection();
1684 dr.setMessage(from_utf8(N_("Mark on")));
1687 case LFUN_MARK_TOGGLE:
1688 cur.selection(false);
1691 dr.setMessage(from_utf8(N_("Mark removed")));
1694 dr.setMessage(from_utf8(N_("Mark set")));
1699 case LFUN_SCREEN_SHOW_CURSOR:
1703 case LFUN_SCREEN_RECENTER:
1707 case LFUN_BIBTEX_DATABASE_ADD: {
1708 Cursor tmpcur = cur;
1709 findInset(tmpcur, { BIBTEX_CODE }, false);
1710 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1713 if (inset->addDatabase(cmd.argument()))
1714 dr.forceBufferUpdate();
1719 case LFUN_BIBTEX_DATABASE_DEL: {
1720 Cursor tmpcur = cur;
1721 findInset(tmpcur, { BIBTEX_CODE }, false);
1722 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1725 if (inset->delDatabase(cmd.argument()))
1726 dr.forceBufferUpdate();
1731 case LFUN_GRAPHICS_UNIFY: {
1733 cur.recordUndoFullBuffer();
1735 DocIterator from, to;
1736 from = cur.selectionBegin();
1737 to = cur.selectionEnd();
1739 string const newId = cmd.getArg(0);
1740 bool fetchId = newId.empty(); //if we wait for groupId from first graphics inset
1742 InsetGraphicsParams grp_par;
1744 InsetGraphics::string2params(graphics::getGroupParams(buffer_, newId), buffer_, grp_par);
1746 if (!from.nextInset()) //move to closest inset
1747 from.forwardInset();
1749 while (!from.empty() && from < to) {
1750 Inset * inset = from.nextInset();
1753 InsetGraphics * ig = inset->asInsetGraphics();
1755 InsetGraphicsParams inspar = ig->getParams();
1760 grp_par.filename = inspar.filename;
1761 ig->setParams(grp_par);
1764 from.forwardInset();
1766 dr.screenUpdate(Update::Force); //needed if triggered from context menu
1770 case LFUN_STATISTICS: {
1771 DocIterator from, to;
1772 if (cur.selection()) {
1773 from = cur.selectionBegin();
1774 to = cur.selectionEnd();
1776 from = doc_iterator_begin(&buffer_);
1777 to = doc_iterator_end(&buffer_);
1779 buffer_.updateStatistics(from, to);
1780 int const words = buffer_.wordCount();
1781 int const chars = buffer_.charCount(false);
1782 int const chars_blanks = buffer_.charCount(true);
1784 if (cur.selection())
1785 message = _("Statistics for the selection:");
1787 message = _("Statistics for the document:");
1790 message += bformat(_("%1$d words"), words);
1792 message += _("One word");
1794 if (chars_blanks != 1)
1795 message += bformat(_("%1$d characters (including blanks)"),
1798 message += _("One character (including blanks)");
1801 message += bformat(_("%1$d characters (excluding blanks)"),
1804 message += _("One character (excluding blanks)");
1806 Alert::information(_("Statistics"), message);
1810 case LFUN_SCREEN_UP:
1811 case LFUN_SCREEN_DOWN: {
1812 Point p = getPos(cur);
1813 // This code has been commented out to enable to scroll down a
1814 // document, even if there are large insets in it (see bug #5465).
1815 /*if (p.y_ < 0 || p.y_ > height_) {
1816 // The cursor is off-screen so recenter before proceeding.
1820 int const scrolled = scroll(act == LFUN_SCREEN_UP
1821 ? -height_ : height_);
1822 if (act == LFUN_SCREEN_UP && scrolled > -height_)
1824 if (act == LFUN_SCREEN_DOWN && scrolled < height_)
1825 p = Point(width_, height_);
1826 bool const in_texted = cur.inTexted();
1827 cur.setCursor(doc_iterator_begin(cur.buffer()));
1828 cur.selHandle(false);
1829 // Force an immediate computation of metrics because we need it below
1830 processUpdateFlags(Update::Force);
1832 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1833 true, act == LFUN_SCREEN_UP);
1834 //FIXME: what to do with cur.x_target()?
1835 bool update = in_texted && cur.bv().checkDepm(cur, old);
1838 if (update || cur.mark())
1839 dr.screenUpdate(Update::Force | Update::FitCursor);
1841 dr.forceBufferUpdate();
1846 string const scroll_type = cmd.getArg(0);
1847 int scroll_step = 0;
1848 if (scroll_type == "line")
1849 scroll_step = d->scrollbarParameters_.single_step;
1850 else if (scroll_type == "page")
1851 scroll_step = d->scrollbarParameters_.page_step;
1854 string const scroll_quantity = cmd.getArg(1);
1855 if (scroll_quantity == "up")
1856 scrollUp(scroll_step);
1857 else if (scroll_quantity == "down")
1858 scrollDown(scroll_step);
1860 int const scroll_value = convert<int>(scroll_quantity);
1862 scroll(scroll_step * scroll_value);
1864 dr.screenUpdate(Update::ForceDraw);
1865 dr.forceBufferUpdate();
1869 case LFUN_SCREEN_UP_SELECT: {
1870 // FIXME: why is the algorithm different from LFUN_SCREEN_UP?
1871 cur.selHandle(true);
1872 if (isTopScreen()) {
1873 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1877 int y = getPos(cur).y_;
1878 int const ymin = y - height_ + defaultRowHeight();
1879 while (y > ymin && cur.up())
1883 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1887 case LFUN_SCREEN_DOWN_SELECT: {
1888 // FIXME: why is the algorithm different from LFUN_SCREEN_DOWN?
1889 cur.selHandle(true);
1890 if (isBottomScreen()) {
1891 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1895 int y = getPos(cur).y_;
1896 int const ymax = y + height_ - defaultRowHeight();
1897 while (y < ymax && cur.down())
1901 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1906 case LFUN_INSET_SELECT_ALL: {
1907 // true if all cells are selected
1908 bool const all_selected = cur.depth() > 1
1909 && cur.selBegin().at_begin()
1910 && cur.selEnd().at_end();
1911 // true if some cells are selected
1912 bool const cells_selected = cur.depth() > 1
1913 && cur.selBegin().at_cell_begin()
1914 && cur.selEnd().at_cell_end();
1915 if (all_selected || (cells_selected && !cur.inset().isTable())) {
1916 // All the contents of the inset if selected, or only at
1917 // least one cell but inset is not a table.
1918 // Select the inset from outside.
1921 cur.selection(true);
1923 } else if (cells_selected) {
1924 // At least one complete cell is selected and inset is a table.
1930 cur.selection(true);
1931 cur.idx() = cur.lastidx();
1932 cur.pit() = cur.lastpit();
1933 cur.pos() = cur.lastpos();
1935 // select current cell
1939 cur.selection(true);
1940 cur.pit() = cur.lastpit();
1941 cur.pos() = cur.lastpos();
1943 cur.setCurrentFont();
1944 dr.screenUpdate(Update::Force);
1949 case LFUN_UNICODE_INSERT: {
1950 if (cmd.argument().empty())
1953 FuncCode code = cur.inset().currentMode() == Inset::MATH_MODE ?
1954 LFUN_MATH_INSERT : LFUN_SELF_INSERT;
1957 docstring const arg = from_utf8(cmd.getArg(i));
1961 LYXERR0("Not a hexstring: " << arg);
1965 char_type c = hexToInt(arg);
1966 if (c >= 32 && c < 0x10ffff) {
1967 LYXERR(Debug::KEY, "Inserting c: " << c);
1968 lyx::dispatch(FuncRequest(code, docstring(1, c)));
1976 // This would be in Buffer class if only Cursor did not
1977 // require a bufferview
1978 case LFUN_INSET_FORALL: {
1979 docstring const name = from_utf8(cmd.getArg(0));
1980 string const commandstr = cmd.getLongArg(1);
1981 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
1983 // an arbitrary number to limit number of iterations
1984 const int max_iter = 100000;
1986 Cursor & curs = d->cursor_;
1987 Cursor const savecur = curs;
1989 if (!curs.nextInset())
1990 curs.forwardInset();
1991 curs.beginUndoGroup();
1992 while(curs && iterations < max_iter) {
1993 Inset * const ins = curs.nextInset();
1996 docstring insname = ins->layoutName();
1997 while (!insname.empty()) {
1998 if (insname == name || name == from_utf8("*")) {
2000 lyx::dispatch(fr, dr);
2004 size_t const i = insname.rfind(':');
2005 if (i == string::npos)
2007 insname = insname.substr(0, i);
2009 // if we did not delete the inset, skip it
2010 if (!curs.nextInset() || curs.nextInset() == ins)
2011 curs.forwardInset();
2015 /** This is a dummy undo record only to remember the cursor
2016 * that has just been set; this will be used on a redo action
2017 * (see ticket #10097)
2019 * FIXME: a better fix would be to have a way to set the
2020 * cursor value directly, but I am not sure it is worth it.
2023 curs.endUndoGroup();
2024 dr.screenUpdate(Update::Force);
2025 dr.forceBufferUpdate();
2027 if (iterations >= max_iter) {
2029 dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
2031 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
2036 case LFUN_BRANCH_ADD_INSERT: {
2037 docstring branch_name = from_utf8(cmd.getArg(0));
2038 if (branch_name.empty())
2039 if (!Alert::askForText(branch_name, _("Branch name")) ||
2040 branch_name.empty())
2043 DispatchResult drtmp;
2044 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
2045 if (drtmp.error()) {
2046 Alert::warning(_("Branch already exists"), drtmp.message());
2049 docstring const sep = buffer_.params().branchlist().separator();
2050 for (docstring const & branch : getVectorFromString(branch_name, sep))
2051 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch));
2055 case LFUN_KEYMAP_OFF:
2056 getIntl().keyMapOn(false);
2059 case LFUN_KEYMAP_PRIMARY:
2060 getIntl().keyMapPrim();
2063 case LFUN_KEYMAP_SECONDARY:
2064 getIntl().keyMapSec();
2067 case LFUN_KEYMAP_TOGGLE:
2068 getIntl().toggleKeyMap();
2071 case LFUN_DIALOG_SHOW_NEW_INSET: {
2072 string const name = cmd.getArg(0);
2073 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2074 if (decodeInsetParam(name, data, buffer_))
2075 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
2077 lyxerr << "Inset type '" << name <<
2078 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
2082 case LFUN_CITATION_INSERT: {
2083 if (argument.empty()) {
2084 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
2087 // we can have one optional argument, delimited by '|'
2088 // citation-insert <key>|<text_before>
2089 // this should be enhanced to also support text_after
2090 // and citation style
2091 string arg = argument;
2093 if (contains(argument, "|")) {
2094 arg = token(argument, '|', 0);
2095 opt1 = token(argument, '|', 1);
2098 // if our cursor is directly in front of or behind a citation inset,
2099 // we will instead add the new key to it.
2100 Inset * inset = cur.nextInset();
2101 if (!inset || inset->lyxCode() != CITE_CODE)
2102 inset = cur.prevInset();
2103 if (inset && inset->lyxCode() == CITE_CODE) {
2104 InsetCitation * icite = static_cast<InsetCitation *>(inset);
2105 if (icite->addKey(arg)) {
2106 dr.forceBufferUpdate();
2107 dr.screenUpdate(Update::FitCursor | Update::SinglePar);
2109 LYXERR0("Discarding optional argument to citation-insert.");
2114 InsetCommandParams icp(CITE_CODE);
2115 icp["key"] = from_utf8(arg);
2117 icp["before"] = from_utf8(opt1);
2119 from_ascii(InsetCitation::last_literal ? "true" : "false");
2120 string icstr = InsetCommand::params2string(icp);
2121 FuncRequest fr(LFUN_INSET_INSERT, icstr);
2126 case LFUN_INSET_APPLY: {
2127 string const name = cmd.getArg(0);
2128 Inset * inset = editedInset(name);
2130 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
2134 // put cursor in front of inset.
2135 if (!setCursorFromInset(inset)) {
2136 LASSERT(false, break);
2139 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
2140 inset->dispatch(cur, fr);
2141 dr.screenUpdate(cur.result().screenUpdate());
2142 if (cur.result().needBufferUpdate())
2143 dr.forceBufferUpdate();
2148 // The change of language of buffer belongs to the Buffer class.
2149 // We have to do it here because we need a cursor for Undo.
2150 // When Undo::recordUndoBufferParams() is implemented someday
2151 // LFUN_BUFFER_LANGUAGE should be handled by the Buffer class.
2152 case LFUN_BUFFER_LANGUAGE: {
2153 Language const * oldL = buffer_.params().language;
2154 Language const * newL = languages.getLanguage(argument);
2155 if (!newL || oldL == newL)
2157 if (oldL->rightToLeft() == newL->rightToLeft()) {
2158 cur.recordUndoFullBuffer();
2159 buffer_.changeLanguage(oldL, newL);
2160 cur.setCurrentFont();
2161 dr.forceBufferUpdate();
2166 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2167 case LFUN_FILE_INSERT_PLAINTEXT: {
2168 bool const as_paragraph = (act == LFUN_FILE_INSERT_PLAINTEXT_PARA);
2169 string const fname = to_utf8(cmd.argument());
2170 if (!FileName::isAbsolute(fname))
2171 dr.setMessage(_("Absolute filename expected."));
2173 insertPlaintextFile(FileName(fname), as_paragraph);
2178 // OK, so try the Buffer itself...
2179 buffer_.dispatch(cmd, dr);
2180 dispatched = dr.dispatched();
2184 buffer_.undo().endUndoGroup();
2185 dr.dispatched(dispatched);
2187 // NOTE: The code below is copied from Cursor::dispatch. If you
2188 // need to modify this, please update the other one too.
2190 // notify insets we just entered/left
2191 if (cursor() != old) {
2192 old.beginUndoGroup();
2194 bool badcursor = notifyCursorLeavesOrEnters(old, cursor());
2196 cursor().fixIfBroken();
2197 resetInlineCompletionPos();
2204 docstring BufferView::requestSelection()
2206 Cursor & cur = d->cursor_;
2208 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
2209 if (!cur.selection()) {
2210 d->xsel_cache_.set = false;
2214 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
2215 if (!d->xsel_cache_.set ||
2216 cur.top() != d->xsel_cache_.cursor ||
2217 cur.realAnchor().top() != d->xsel_cache_.anchor)
2219 d->xsel_cache_.cursor = cur.top();
2220 d->xsel_cache_.anchor = cur.realAnchor().top();
2221 d->xsel_cache_.set = cur.selection();
2222 return cur.selectionAsString(false);
2228 void BufferView::clearSelection()
2230 d->cursor_.clearSelection();
2231 // Clear the selection buffer. Otherwise a subsequent
2232 // middle-mouse-button paste would use the selection buffer,
2233 // not the more current external selection.
2234 cap::clearSelection();
2235 d->xsel_cache_.set = false;
2236 // The buffer did not really change, but this causes the
2237 // redraw we need because we cleared the selection above.
2238 buffer_.changed(false);
2242 void BufferView::resize(int width, int height)
2244 // Update from work area
2248 // Clear the paragraph height cache.
2249 d->par_height_.clear();
2250 // Redo the metrics.
2255 Inset const * BufferView::getCoveringInset(Text const & text,
2258 TextMetrics & tm = d->text_metrics_[&text];
2259 Inset * inset = tm.checkInsetHit(x, y);
2263 if (!inset->descendable(*this))
2264 // No need to go further down if the inset is not
2268 size_t cell_number = inset->nargs();
2269 // Check all the inner cell.
2270 for (size_t i = 0; i != cell_number; ++i) {
2271 Text const * inner_text = inset->getText(i);
2274 Inset const * inset_deeper =
2275 getCoveringInset(*inner_text, x, y);
2277 return inset_deeper;
2285 void BufferView::updateHoveredInset() const
2287 // Get inset under mouse, if there is one.
2288 int const x = d->mouse_position_cache_.x_;
2289 int const y = d->mouse_position_cache_.y_;
2290 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
2292 d->clickable_inset_ = covering_inset && covering_inset->clickable(*this, x, y);
2294 if (covering_inset == d->last_inset_)
2295 // Same inset, no need to do anything...
2298 bool need_redraw = false;
2299 if (d->last_inset_) {
2300 // Remove the hint on the last hovered inset (if any).
2301 need_redraw |= d->last_inset_->setMouseHover(this, false);
2302 d->last_inset_ = nullptr;
2305 if (covering_inset && covering_inset->setMouseHover(this, true)) {
2307 // Only the insets that accept the hover state, do
2308 // clear the last_inset_, so only set the last_inset_
2309 // member if the hovered setting is accepted.
2310 d->last_inset_ = covering_inset;
2314 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
2315 << d->mouse_position_cache_.x_ << ", "
2316 << d->mouse_position_cache_.y_ << ")");
2318 d->update_strategy_ = DecorationUpdate;
2320 // This event (moving without mouse click) is not passed further.
2321 // This should be changed if it is further utilized.
2322 buffer_.changed(false);
2327 void BufferView::clearLastInset(Inset * inset) const
2329 if (d->last_inset_ != inset) {
2330 LYXERR0("Wrong last_inset!");
2333 d->last_inset_ = nullptr;
2337 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
2339 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
2341 // This is only called for mouse related events including
2342 // LFUN_FILE_OPEN generated by drag-and-drop.
2343 FuncRequest cmd = cmd0;
2345 Cursor old = cursor();
2347 cur.push(buffer_.inset());
2348 cur.selection(d->cursor_.selection());
2350 // Either the inset under the cursor or the
2351 // surrounding Text will handle this event.
2353 // make sure we stay within the screen...
2354 cmd.set_y(min(max(cmd.y(), -1), height_));
2356 d->mouse_position_cache_.x_ = cmd.x();
2357 d->mouse_position_cache_.y_ = cmd.y();
2359 if (cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
2360 updateHoveredInset();
2364 // Build temporary cursor.
2365 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x(), cmd.y());
2367 // If inset is not editable, cur.pos() might point behind the
2368 // inset (depending on cmd.x(), cmd.y()). This is needed for
2369 // editing to fix bug 9628, but e.g. the context menu needs a
2370 // cursor in front of the inset.
2371 if ((inset->hasSettings() || !inset->contextMenuName().empty()
2372 || inset->lyxCode() == SEPARATOR_CODE) &&
2373 cur.nextInset() != inset && cur.prevInset() == inset)
2375 } else if (cur.inTexted() && cur.pos()
2376 && cur.paragraph().isEnvSeparator(cur.pos() - 1)) {
2377 // Always place cursor in front of a separator inset.
2381 // Put anchor at the same position.
2384 cur.beginUndoGroup();
2386 // Try to dispatch to an non-editable inset near this position
2387 // via the temp cursor. If the inset wishes to change the real
2388 // cursor it has to do so explicitly by using
2389 // cur.bv().cursor() = cur; (or similar)
2391 inset->dispatch(cur, cmd);
2393 // Now dispatch to the temporary cursor. If the real cursor should
2394 // be modified, the inset's dispatch has to do so explicitly.
2395 if (!inset || !cur.result().dispatched())
2398 // Notify left insets
2400 bool badcursor = old.fixIfBroken() | cur.fixIfBroken();
2401 badcursor |= notifyCursorLeavesOrEnters(old, cur);
2403 cursor().fixIfBroken();
2408 // Do we have a selection?
2409 theSelection().haveSelection(cursor().selection());
2411 if (cur.needBufferUpdate()) {
2412 cur.clearBufferUpdate();
2413 buffer().updateBuffer();
2416 // If the command has been dispatched,
2417 if (cur.result().dispatched() || cur.result().screenUpdate())
2418 processUpdateFlags(cur.result().screenUpdate());
2422 int BufferView::minVisiblePart()
2424 return 2 * defaultRowHeight();
2428 int BufferView::scroll(int y)
2431 return scrollDown(y);
2433 return scrollUp(-y);
2438 int BufferView::scrollDown(int offset)
2440 Text * text = &buffer_.text();
2441 TextMetrics & tm = d->text_metrics_[text];
2442 int const ymax = height_ + offset;
2444 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2445 int bottom_pos = last.second->position() + last.second->descent();
2446 if (lyxrc.scroll_below_document)
2447 bottom_pos += height_ - minVisiblePart();
2448 if (last.first + 1 == int(text->paragraphs().size())) {
2449 if (bottom_pos <= height_)
2451 offset = min(offset, bottom_pos - height_);
2454 if (bottom_pos > ymax)
2456 tm.newParMetricsDown();
2458 d->anchor_ypos_ -= offset;
2463 int BufferView::scrollUp(int offset)
2465 Text * text = &buffer_.text();
2466 TextMetrics & tm = d->text_metrics_[text];
2467 int ymin = - offset;
2469 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2470 int top_pos = first.second->position() - first.second->ascent();
2471 if (first.first == 0) {
2474 offset = min(offset, - top_pos);
2479 tm.newParMetricsUp();
2481 d->anchor_ypos_ += offset;
2486 bool BufferView::setCursorFromRow(int row)
2488 TexRow::TextEntry start, end;
2489 tie(start,end) = buffer_.texrow().getEntriesFromRow(row);
2490 LYXERR(Debug::LATEX,
2491 "setCursorFromRow: for row " << row << ", TexRow has found "
2492 "start (id=" << start.id << ",pos=" << start.pos << "), "
2493 "end (id=" << end.id << ",pos=" << end.pos << ")");
2494 return setCursorFromEntries(start, end);
2498 bool BufferView::setCursorFromEntries(TexRow::TextEntry start,
2499 TexRow::TextEntry end)
2501 DocIterator dit_start, dit_end;
2502 tie(dit_start,dit_end) =
2503 TexRow::getDocIteratorsFromEntries(start, end, buffer_);
2506 // Setting selection start
2507 d->cursor_.clearSelection();
2508 setCursor(dit_start);
2509 // Setting selection end
2511 d->cursor_.resetAnchor();
2512 setCursorSelectionTo(dit_end);
2518 bool BufferView::setCursorFromInset(Inset const * inset)
2520 // are we already there?
2521 if (cursor().nextInset() == inset)
2524 // Inset is not at cursor position. Find it in the document.
2527 while (cur && cur.nextInset() != inset)
2538 void BufferView::gotoLabel(docstring const & label)
2541 bool have_inactive = false;
2542 for (Buffer const * buf : buffer().allRelatives()) {
2544 for (TocItem const & item : *buf->tocBackend().toc("label")) {
2545 if (label == item.str() && item.isOutput()) {
2546 lyx::dispatch(item.action());
2549 // If we find an inactive label, save it for the case
2550 // that no active one is there
2551 if (label == item.str() && !have_inactive) {
2552 have_inactive = true;
2553 action = item.action();
2557 // We only found an inactive label. Go there.
2559 lyx::dispatch(action);
2563 TextMetrics const & BufferView::textMetrics(Text const * t) const
2565 return const_cast<BufferView *>(this)->textMetrics(t);
2569 TextMetrics & BufferView::textMetrics(Text const * t)
2572 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
2573 if (tmc_it == d->text_metrics_.end()) {
2574 tmc_it = d->text_metrics_.emplace(std::piecewise_construct,
2575 std::forward_as_tuple(t),
2576 std::forward_as_tuple(this, const_cast<Text *>(t))).first;
2578 return tmc_it->second;
2582 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2585 return textMetrics(t).parMetrics(pit);
2589 int BufferView::workHeight() const
2595 void BufferView::setCursor(DocIterator const & dit)
2598 size_t const n = dit.depth();
2599 for (size_t i = 0; i < n; ++i)
2600 dit[i].inset().edit(d->cursor_, true);
2602 d->cursor_.setCursor(dit);
2603 d->cursor_.selection(false);
2604 d->cursor_.setCurrentFont();
2606 // It seems on general grounds as if this is probably needed, but
2607 // it is not yet clear.
2608 // See bug #7394 and r38388.
2609 // d->cursor.resetAnchor();
2613 void BufferView::setCursorSelectionTo(DocIterator const & dit)
2615 size_t const n = dit.depth();
2616 for (size_t i = 0; i < n; ++i)
2617 dit[i].inset().edit(d->cursor_, true);
2619 d->cursor_.selection(true);
2620 d->cursor_.setCursorSelectionTo(dit);
2621 d->cursor_.setCurrentFont();
2625 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2627 // Would be wrong to delete anything if we have a selection.
2628 if (cur.selection())
2631 bool need_anchor_change = false;
2632 bool changed = Text::deleteEmptyParagraphMechanism(cur, old,
2633 need_anchor_change);
2635 if (need_anchor_change)
2643 // we would rather not do this here, but it needs to be done before
2644 // the changed() signal is sent.
2645 buffer_.updateBuffer();
2647 buffer_.changed(true);
2652 bool BufferView::mouseSetCursor(Cursor & cur, bool const select)
2654 LASSERT(&cur.bv() == this, return false);
2657 // this event will clear selection so we save selection for
2658 // persistent selection
2659 cap::saveSelection(cursor());
2661 d->cursor_.macroModeClose();
2662 // If a macro has been finalized, the cursor might have been broken
2665 // Has the cursor just left the inset?
2666 bool const leftinset = (&d->cursor_.inset() != &cur.inset());
2668 d->cursor_.fixIfBroken();
2670 // do the dEPM magic if needed
2671 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2672 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2673 // the leftinset bool would not be necessary (badcursor instead).
2674 bool update = leftinset;
2677 d->cursor_.setSelection();
2678 d->cursor_.setCursorSelectionTo(cur);
2680 if (d->cursor_.inTexted())
2681 update |= checkDepm(cur, d->cursor_);
2682 d->cursor_.resetAnchor();
2683 d->cursor_.setCursor(cur);
2684 d->cursor_.clearSelection();
2686 d->cursor_.boundary(cur.boundary());
2687 d->cursor_.finishUndo();
2688 d->cursor_.setCurrentFont();
2690 cur.forceBufferUpdate();
2695 void BufferView::putSelectionAt(DocIterator const & cur,
2696 int length, bool backwards)
2698 d->cursor_.clearSelection();
2704 d->cursor_.pos() += length;
2705 d->cursor_.setSelection(d->cursor_, -length);
2707 d->cursor_.setSelection(d->cursor_, length);
2712 bool BufferView::selectIfEmpty(DocIterator & cur)
2714 if ((cur.inTexted() && !cur.paragraph().empty())
2715 || (cur.inMathed() && !cur.cell().empty()))
2718 pit_type const beg_pit = cur.pit();
2720 // The paragraph associated to this item isn't
2721 // the first one, so it can be selected
2724 // We have to resort to select the space between the
2725 // end of this item and the begin of the next one
2729 // If it is the only item in the document,
2730 // nothing can be selected
2733 pit_type const end_pit = cur.pit();
2734 pos_type const end_pos = cur.pos();
2735 d->cursor_.clearSelection();
2737 d->cursor_.setCursor(cur);
2738 d->cursor_.pit() = beg_pit;
2739 d->cursor_.pos() = 0;
2740 d->cursor_.selection(false);
2741 d->cursor_.resetAnchor();
2742 d->cursor_.pit() = end_pit;
2743 d->cursor_.pos() = end_pos;
2744 d->cursor_.setSelection();
2749 Cursor & BufferView::cursor()
2755 Cursor const & BufferView::cursor() const
2761 bool BufferView::singleParUpdate()
2763 Text & buftext = buffer_.text();
2764 pit_type const bottom_pit = d->cursor_.bottom().pit();
2765 TextMetrics & tm = textMetrics(&buftext);
2766 int old_height = tm.parMetrics(bottom_pit).height();
2768 // make sure inline completion pointer is ok
2769 if (d->inlineCompletionPos_.fixIfBroken())
2770 d->inlineCompletionPos_ = DocIterator();
2772 // In Single Paragraph mode, rebreak only
2773 // the (main text, not inset!) paragraph containing the cursor.
2774 // (if this paragraph contains insets etc., rebreaking will
2775 // recursively descend)
2776 tm.redoParagraph(bottom_pit);
2777 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
2778 if (pm.height() != old_height)
2779 // Paragraph height has changed so we cannot proceed to
2780 // the singlePar optimisation.
2783 tm.updatePosCache(bottom_pit);
2785 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2786 << " y2: " << pm.position() + pm.descent()
2787 << " pit: " << bottom_pit
2788 << " singlepar: 1");
2793 void BufferView::updateMetrics()
2795 updateMetrics(d->update_flags_);
2796 d->update_strategy_ = FullScreenUpdate;
2800 void BufferView::updateMetrics(Update::flags & update_flags)
2802 if (height_ == 0 || width_ == 0)
2805 Text & buftext = buffer_.text();
2806 pit_type const npit = int(buftext.paragraphs().size());
2808 // Clear out the position cache in case of full screen redraw,
2809 d->coord_cache_.clear();
2810 d->math_rows_.clear();
2812 // Clear out paragraph metrics to avoid having invalid metrics
2813 // in the cache from paragraphs not relayouted below
2814 // The complete text metrics will be redone.
2815 d->text_metrics_.clear();
2817 TextMetrics & tm = textMetrics(&buftext);
2819 // make sure inline completion pointer is ok
2820 if (d->inlineCompletionPos_.fixIfBroken())
2821 d->inlineCompletionPos_ = DocIterator();
2823 if (d->anchor_pit_ >= npit)
2824 // The anchor pit must have been deleted...
2825 d->anchor_pit_ = npit - 1;
2827 // Rebreak anchor paragraph.
2828 tm.redoParagraph(d->anchor_pit_);
2829 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2832 if (d->anchor_pit_ == 0) {
2833 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2835 // Complete buffer visible? Then it's easy.
2836 if (scrollRange == 0)
2837 d->anchor_ypos_ = anchor_pm.ascent();
2839 // avoid empty space above the first row
2840 d->anchor_ypos_ = min(d->anchor_ypos_, anchor_pm.ascent());
2843 anchor_pm.setPosition(d->anchor_ypos_);
2844 tm.updatePosCache(d->anchor_pit_);
2846 LYXERR(Debug::PAINTING, "metrics: "
2847 << " anchor pit = " << d->anchor_pit_
2848 << " anchor ypos = " << d->anchor_ypos_);
2850 // Redo paragraphs above anchor if necessary.
2851 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2852 // We are now just above the anchor paragraph.
2853 pit_type pit1 = d->anchor_pit_ - 1;
2854 for (; pit1 >= 0 && y1 >= 0; --pit1) {
2855 tm.redoParagraph(pit1);
2856 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2858 // Save the paragraph position in the cache.
2860 tm.updatePosCache(pit1);
2864 // Redo paragraphs below the anchor if necessary.
2865 int y2 = d->anchor_ypos_ + anchor_pm.descent();
2866 // We are now just below the anchor paragraph.
2867 pit_type pit2 = d->anchor_pit_ + 1;
2868 for (; pit2 < npit && y2 <= height_; ++pit2) {
2869 tm.redoParagraph(pit2);
2870 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2872 // Save the paragraph position in the cache.
2874 tm.updatePosCache(pit2);
2878 LYXERR(Debug::PAINTING, "Metrics: "
2879 << " anchor pit = " << d->anchor_pit_
2880 << " anchor ypos = " << d->anchor_ypos_
2883 << " pit1 = " << pit1
2884 << " pit2 = " << pit2);
2886 // metrics is done, full drawing is necessary now
2887 update_flags = (update_flags & ~Update::Force) | Update::ForceDraw;
2889 // Now update the positions of insets in the cache.
2892 if (lyxerr.debugging(Debug::WORKAREA)) {
2893 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2894 d->coord_cache_.dump();
2899 void BufferView::updatePosCache()
2901 // this is the "nodraw" drawing stage: only set the positions of the
2902 // insets in metrics cache.
2903 frontend::NullPainter np;
2908 void BufferView::insertLyXFile(FileName const & fname, bool const ignorelang)
2910 LASSERT(d->cursor_.inTexted(), return);
2912 // Get absolute path of file and add ".lyx"
2913 // to the filename if necessary
2914 FileName filename = fileSearch(string(), fname.absFileName(), "lyx");
2916 docstring const disp_fn = makeDisplayPath(filename.absFileName());
2917 // emit message signal.
2918 message(bformat(_("Inserting document %1$s..."), disp_fn));
2921 Buffer buf(filename.absFileName(), false);
2922 if (buf.loadLyXFile() == Buffer::ReadSuccess) {
2923 ErrorList & el = buffer_.errorList("Parse");
2924 // Copy the inserted document error list into the current buffer one.
2925 el = buf.errorList("Parse");
2926 ParagraphList & pars = buf.paragraphs();
2928 // set main language of imported file to context language
2929 buf.changeLanguage(buf.language(), d->cursor_.getFont().language());
2930 buffer_.undo().recordUndo(d->cursor_);
2931 cap::pasteParagraphList(d->cursor_, pars,
2932 buf.params().documentClassPtr(), el);
2933 res = _("Document %1$s inserted.");
2935 res = _("Could not insert document %1$s");
2938 buffer_.changed(true);
2939 // emit message signal.
2940 message(bformat(res, disp_fn));
2944 Point BufferView::coordOffset(DocIterator const & dit) const
2950 // Addup contribution of nested insets, from inside to outside,
2951 // keeping the outer paragraph for a special handling below
2952 for (size_t i = dit.depth() - 1; i >= 1; --i) {
2953 CursorSlice const & sl = dit[i];
2957 // get relative position inside sl.inset()
2958 sl.inset().cursorPos(*this, sl, dit.boundary() && (i + 1 == dit.depth()), xx, yy);
2960 // Make relative position inside of the edited inset relative to sl.inset()
2964 // In case of an RTL inset, the edited inset will be positioned to the left
2967 bool boundary_i = dit.boundary() && i + 1 == dit.depth();
2968 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2973 // remember width for the case that sl.inset() is positioned in an RTL inset
2974 lastw = sl.inset().dimension(*this).wid;
2976 //lyxerr << "Cursor::getPos, i: "
2977 // << i << " x: " << xx << " y: " << y << endl;
2980 // Add contribution of initial rows of outermost paragraph
2981 CursorSlice const & sl = dit[0];
2982 TextMetrics const & tm = textMetrics(sl.text());
2983 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2985 LBUFERR(!pm.rows().empty());
2986 y -= pm.rows()[0].ascent();
2988 // FIXME: document this mess
2990 if (sl.pos() > 0 && dit.depth() == 1) {
2992 if (pos && dit.boundary())
2994 // lyxerr << "coordOffset: boundary:" << dit.boundary() << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2995 rend = pm.pos2row(pos);
2997 rend = pm.pos2row(sl.pos());
2999 size_t rend = pm.pos2row(sl.pos());
3001 for (size_t rit = 0; rit != rend; ++rit)
3002 y += pm.rows()[rit].height();
3003 y += pm.rows()[rend].ascent();
3005 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
3007 // Make relative position from the nested inset now bufferview absolute.
3008 int xx = bottom_tm.cursorX(dit.bottom(), dit.boundary() && dit.depth() == 1);
3011 // In the RTL case place the nested inset at the left of the cursor in
3012 // the outer paragraph
3013 bool boundary_1 = dit.boundary() && 1 == dit.depth();
3014 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
3022 Point BufferView::getPos(DocIterator const & dit) const
3024 if (!paragraphVisible(dit))
3025 return Point(-1, -1);
3027 CursorSlice const & bot = dit.bottom();
3028 TextMetrics const & tm = textMetrics(bot.text());
3030 // offset from outer paragraph
3031 Point p = coordOffset(dit);
3032 p.y_ += tm.parMetrics(bot.pit()).position();
3037 bool BufferView::paragraphVisible(DocIterator const & dit) const
3039 CursorSlice const & bot = dit.bottom();
3040 TextMetrics const & tm = textMetrics(bot.text());
3042 return tm.contains(bot.pit());
3046 void BufferView::caretPosAndHeight(Point & p, int & h) const
3049 Cursor const & cur = cursor();
3050 if (cur.inMathed()) {
3051 MathRow const & mrow = mathRow(&cur.cell());
3052 asc = mrow.caret_ascent;
3053 des = mrow.caret_descent;
3055 Font const font = cur.real_current_font;
3056 frontend::FontMetrics const & fm = theFontMetrics(font);
3057 asc = fm.maxAscent();
3058 des = fm.maxDescent();
3066 bool BufferView::caretInView() const
3068 if (!paragraphVisible(cursor()))
3072 caretPosAndHeight(p, h);
3074 // does the cursor touch the screen ?
3075 if (p.y_ + h < 0 || p.y_ >= workHeight())
3081 int BufferView::horizScrollOffset() const
3083 return d->horiz_scroll_offset_;
3087 int BufferView::horizScrollOffset(Text const * text,
3088 pit_type pit, pos_type pos) const
3090 // Is this a row that is currently scrolled?
3091 if (!d->current_row_slice_.empty()
3092 && &text->inset() == d->current_row_slice_.inset().asInsetText()
3093 && pit == d->current_row_slice_.pit()
3094 && pos == d->current_row_slice_.pos())
3095 return d->horiz_scroll_offset_;
3100 void BufferView::setCurrentRowSlice(CursorSlice const & rowSlice)
3102 // nothing to do if the cursor was already on this row
3103 if (d->current_row_slice_ == rowSlice)
3106 // if the (previous) current row was scrolled, we have to
3107 // remember it in order to repaint it next time.
3108 if (d->horiz_scroll_offset_ != 0) {
3109 // search the old row in cache and mark it changed
3110 for (auto & tm_pair : d->text_metrics_) {
3111 if (&tm_pair.first->inset() == rowSlice.inset().asInsetText()) {
3112 tm_pair.second.setRowChanged(rowSlice.pit(), rowSlice.pos());
3113 // We found it, no need to continue.
3119 // Since we changed row, the scroll offset is not valid anymore
3120 d->horiz_scroll_offset_ = 0;
3121 d->current_row_slice_ = rowSlice;
3125 void BufferView::checkCursorScrollOffset()
3127 CursorSlice rowSlice = d->cursor_.bottom();
3128 TextMetrics const & tm = textMetrics(rowSlice.text());
3130 // Stop if metrics have not been computed yet, since it means
3131 // that there is nothing to do.
3132 if (!tm.contains(rowSlice.pit()))
3134 ParagraphMetrics const & pm = tm.parMetrics(rowSlice.pit());
3135 Row const & row = pm.getRow(rowSlice.pos(),
3136 d->cursor_.boundary() && rowSlice == d->cursor_.top());
3137 rowSlice.pos() = row.pos();
3139 // Set the row on which the cursor lives.
3140 setCurrentRowSlice(rowSlice);
3142 // Current x position of the cursor in pixels
3143 int cur_x = getPos(d->cursor_).x_;
3145 // Horizontal scroll offset of the cursor row in pixels
3146 int offset = d->horiz_scroll_offset_;
3147 int const MARGIN = 2 * theFontMetrics(d->cursor_.real_current_font).em()
3149 if (row.right_x() <= workWidth() - row.right_margin) {
3150 // Row is narrower than the work area, no offset needed.
3153 if (cur_x - offset < MARGIN) {
3154 // cursor would be too far right
3155 offset = cur_x - MARGIN;
3156 } else if (cur_x - offset > workWidth() - MARGIN) {
3157 // cursor would be too far left
3158 offset = cur_x - workWidth() + MARGIN;
3160 // Correct the offset to make sure that we do not scroll too much
3163 if (row.right_x() - offset < workWidth() - row.right_margin)
3164 offset = row.right_x() - workWidth() + row.right_margin;
3167 //lyxerr << "cur_x=" << cur_x << ", offset=" << offset << ", row.wid=" << row.width() << ", margin=" << MARGIN << endl;
3169 if (offset != d->horiz_scroll_offset_)
3170 LYXERR(Debug::PAINTING, "Horiz. scroll offset changed from "
3171 << d->horiz_scroll_offset_ << " to " << offset);
3173 if (d->update_strategy_ == NoScreenUpdate
3174 && offset != d->horiz_scroll_offset_) {
3175 // FIXME: if one uses SingleParUpdate, then home/end
3176 // will not work on long rows. Why?
3177 d->update_strategy_ = FullScreenUpdate;
3180 d->horiz_scroll_offset_ = offset;
3184 void BufferView::draw(frontend::Painter & pain, bool paint_caret)
3186 if (height_ == 0 || width_ == 0)
3188 LYXERR(Debug::PAINTING, (pain.isNull() ? "\t\t--- START NODRAW ---"
3189 : "\t\t*** START DRAWING ***"));
3190 Text & text = buffer_.text();
3191 TextMetrics const & tm = d->text_metrics_[&text];
3192 int const y = tm.first().second->position();
3193 PainterInfo pi(this, pain);
3195 // Check whether the row where the cursor lives needs to be scrolled.
3196 // Update the drawing strategy if needed.
3197 checkCursorScrollOffset();
3199 switch (d->update_strategy_) {
3201 case NoScreenUpdate:
3202 // no screen painting is actually needed. In nodraw stage
3203 // however, the different coordinates of insets and paragraphs
3204 // needs to be updated.
3205 LYXERR(Debug::PAINTING, "Strategy: NoScreenUpdate");
3206 if (pain.isNull()) {
3207 pi.full_repaint = true;
3210 pi.full_repaint = false;
3215 case SingleParUpdate:
3216 pi.full_repaint = false;
3217 LYXERR(Debug::PAINTING, "Strategy: SingleParUpdate");
3218 // In general, only the current row of the outermost paragraph
3219 // will be redrawn. Particular cases where selection spans
3220 // multiple paragraph are correctly detected in TextMetrics.
3224 case DecorationUpdate:
3225 // FIXME: We should also distinguish DecorationUpdate to avoid text
3226 // drawing if possible. This is not possible to do easily right now
3227 // because of the single backing pixmap.
3229 case FullScreenUpdate:
3231 LYXERR(Debug::PAINTING,
3232 ((d->update_strategy_ == FullScreenUpdate)
3233 ? "Strategy: FullScreenUpdate"
3234 : "Strategy: DecorationUpdate"));
3236 // The whole screen, including insets, will be refreshed.
3237 pi.full_repaint = true;
3239 // Clear background.
3240 pain.fillRectangle(0, 0, width_, height_,
3241 pi.backgroundColor(&buffer_.inset()));
3246 // and possibly grey out below
3247 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3248 int const y2 = lastpm.second->position() + lastpm.second->descent();
3251 Color color = buffer().isInternal()
3252 ? Color_background : Color_bottomarea;
3253 pain.fillRectangle(0, y2, width_, height_ - y2, color);
3257 LYXERR(Debug::PAINTING, (pain.isNull() ? "\t\t --- END NODRAW ---"
3258 : "\t\t *** END DRAWING ***"));
3260 // The scrollbar needs an update.
3263 // Normalize anchor for next time
3264 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
3265 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3266 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
3267 ParagraphMetrics const & pm = tm.parMetrics(pit);
3268 if (pm.position() + pm.descent() > 0) {
3269 if (d->anchor_pit_ != pit
3270 || d->anchor_ypos_ != pm.position())
3271 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
3272 << " anchor ypos = " << d->anchor_ypos_);
3273 d->anchor_pit_ = pit;
3274 d->anchor_ypos_ = pm.position();
3278 if (!pain.isNull()) {
3279 // reset the update flags, everything has been done
3280 d->update_flags_ = Update::None;
3283 // If a caret has to be painted, mark its text row as dirty to
3284 //make sure that it will be repainted on next redraw.
3285 /* FIXME: investigate whether this can be avoided when the cursor did not
3289 Row const & caret_row = d->cursor_.textRow();
3290 caret_row.changed(true);
3295 void BufferView::message(docstring const & msg)
3298 d->gui_->message(msg);
3302 void BufferView::showDialog(string const & name)
3305 d->gui_->showDialog(name, string());
3309 void BufferView::showDialog(string const & name,
3310 string const & data, Inset * inset)
3313 d->gui_->showDialog(name, data, inset);
3317 void BufferView::updateDialog(string const & name, string const & data)
3320 d->gui_->updateDialog(name, data);
3324 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
3330 // FIXME: Move this out of BufferView again
3331 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
3333 if (!fname.isReadableFile()) {
3334 docstring const error = from_ascii(strerror(errno));
3335 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3336 docstring const text =
3337 bformat(_("Could not read the specified document\n"
3338 "%1$s\ndue to the error: %2$s"), file, error);
3339 Alert::error(_("Could not read file"), text);
3343 if (!fname.isReadableFile()) {
3344 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3345 docstring const text =
3346 bformat(_("%1$s\n is not readable."), file);
3347 Alert::error(_("Could not open file"), text);
3351 // FIXME UNICODE: We don't know the encoding of the file
3352 docstring file_content = fname.fileContents("UTF-8");
3353 if (file_content.empty()) {
3354 Alert::error(_("Reading not UTF-8 encoded file"),
3355 _("The file is not UTF-8 encoded.\n"
3356 "It will be read as local 8Bit-encoded.\n"
3357 "If this does not give the correct result\n"
3358 "then please change the encoding of the file\n"
3359 "to UTF-8 with a program other than LyX.\n"));
3360 file_content = fname.fileContents("local8bit");
3363 return normalize_c(file_content);
3367 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
3369 docstring const tmpstr = contentsOfPlaintextFile(f);
3374 Cursor & cur = cursor();
3375 cap::replaceSelection(cur);
3376 buffer_.undo().recordUndo(cur);
3378 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
3380 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
3382 buffer_.changed(true);
3386 docstring const & BufferView::inlineCompletion() const
3388 return d->inlineCompletion_;
3392 size_t const & BufferView::inlineCompletionUniqueChars() const
3394 return d->inlineCompletionUniqueChars_;
3398 DocIterator const & BufferView::inlineCompletionPos() const
3400 return d->inlineCompletionPos_;
3404 void BufferView::resetInlineCompletionPos()
3406 d->inlineCompletionPos_ = DocIterator();
3410 bool samePar(DocIterator const & a, DocIterator const & b)
3412 if (a.empty() && b.empty())
3414 if (a.empty() || b.empty())
3416 if (a.depth() != b.depth())
3418 return &a.innerParagraph() == &b.innerParagraph();
3422 void BufferView::setInlineCompletion(Cursor const & cur, DocIterator const & pos,
3423 docstring const & completion, size_t uniqueChars)
3425 uniqueChars = min(completion.size(), uniqueChars);
3426 bool changed = d->inlineCompletion_ != completion
3427 || d->inlineCompletionUniqueChars_ != uniqueChars;
3428 bool singlePar = true;
3429 d->inlineCompletion_ = completion;
3430 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
3432 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
3435 DocIterator const & old = d->inlineCompletionPos_;
3437 //lyxerr << "inlineCompletionPos changed" << std::endl;
3438 // old or pos are in another paragraph?
3439 if ((!samePar(cur, pos) && !pos.empty())
3440 || (!samePar(cur, old) && !old.empty())) {
3442 //lyxerr << "different paragraph" << std::endl;
3444 d->inlineCompletionPos_ = pos;
3449 if (singlePar && !(cur.result().screenUpdate() & Update::Force))
3450 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
3452 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::Force);
3457 bool BufferView::clickableInset() const
3459 return d->clickable_inset_;