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"
44 #include "MetricsInfo.h"
45 #include "Paragraph.h"
46 #include "ParagraphParameters.h"
47 #include "ParIterator.h"
50 #include "TextClass.h"
51 #include "TextMetrics.h"
53 #include "TocBackend.h"
55 #include "WordLangTuple.h"
57 #include "insets/InsetBibtex.h"
58 #include "insets/InsetCommand.h" // ChangeRefs
59 #include "insets/InsetExternal.h"
60 #include "insets/InsetGraphics.h"
61 #include "insets/InsetRef.h"
62 #include "insets/InsetText.h"
63 #include "insets/InsetNote.h"
65 #include "frontends/alert.h"
66 #include "frontends/Application.h"
67 #include "frontends/Delegates.h"
68 #include "frontends/FontMetrics.h"
69 #include "frontends/Painter.h"
70 #include "frontends/Selection.h"
72 #include "graphics/Previews.h"
74 #include "support/convert.h"
75 #include "support/debug.h"
76 #include "support/ExceptionMessage.h"
77 #include "support/filetools.h"
78 #include "support/gettext.h"
79 #include "support/lstrings.h"
80 #include "support/Package.h"
81 #include "support/types.h"
90 using namespace lyx::support;
94 namespace Alert = frontend::Alert;
98 /// Return an inset of this class if it exists at the current cursor position
100 T * getInsetByCode(Cursor const & cur, InsetCode code)
102 DocIterator it = cur;
103 Inset * inset = it.nextInset();
104 if (inset && inset->lyxCode() == code)
105 return static_cast<T*>(inset);
110 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
113 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
114 docstring const & contents)
116 DocIterator tmpdit = dit;
119 Inset const * inset = tmpdit.nextInset();
121 && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
122 && (contents.empty() ||
123 static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
127 tmpdit.forwardInset();
134 /// Looks for next inset with one of the given codes.
135 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
139 DocIterator tmpdit = dit;
140 tmpdit.forwardInset();
145 Inset const * inset = tmpdit.nextInset();
147 && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
148 contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
152 if (!findNextInset(tmpdit, codes, contents)) {
153 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
154 Inset * inset = &tmpdit.bottom().inset();
155 tmpdit = doc_iterator_begin(&inset->buffer(), inset);
156 if (!findNextInset(tmpdit, codes, contents))
168 /// Looks for next inset with the given code
169 void findInset(DocIterator & dit, InsetCode code, bool same_content)
171 findInset(dit, vector<InsetCode>(1, code), same_content);
175 /// Moves cursor to the next inset with one of the given codes.
176 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
179 Cursor tmpcur = bv->cursor();
180 if (!findInset(tmpcur, codes, same_content)) {
181 bv->cursor().message(_("No more insets"));
185 tmpcur.clearSelection();
186 bv->setCursor(tmpcur);
191 /// Moves cursor to the next inset with given code.
192 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
194 gotoInset(bv, vector<InsetCode>(1, code), same_content);
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): wh_(0), cursor_(bv),
220 anchor_pit_(0), anchor_ypos_(0),
221 inlineCompletionUniqueChars_(0),
222 last_inset_(0), bookmark_edit_position_(0), gui_(0)
226 ScrollbarParameters scrollbarParameters_;
228 ScreenUpdateStrategy update_strategy_;
230 CoordCache coord_cache_;
232 /// Estimated average par height for scrollbar.
234 /// this is used to handle XSelection events in the right manner.
243 pit_type anchor_pit_;
247 vector<int> par_height_;
250 DocIterator inlineCompletionPos_;
252 docstring inlineCompletion_;
254 size_t inlineCompletionUniqueChars_;
256 /// keyboard mapping object.
259 /// last visited inset.
260 /** kept to send setMouseHover(false).
261 * Not owned, so don't delete.
265 // cache for id of the paragraph which was edited the last time
266 int bookmark_edit_position_;
268 mutable TextMetricsCache text_metrics_;
271 /** Not owned, so don't delete.
273 frontend::GuiBufferViewDelegate * gui_;
275 /// Cache for Find Next
276 FuncRequest search_request_cache_;
280 BufferView::BufferView(Buffer & buf)
281 : width_(0), height_(0), full_screen_(false), buffer_(buf),
282 d(new Private(*this))
284 d->xsel_cache_.set = false;
285 d->intl_.initKeyMapper(lyxrc.use_kbmap);
287 d->cursor_.setBuffer(&buf);
288 d->cursor_.push(buffer_.inset());
289 d->cursor_.resetAnchor();
290 d->cursor_.setCurrentFont();
292 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
293 thePreviews().generateBufferPreviews(buffer_);
297 BufferView::~BufferView()
299 // current buffer is going to be switched-off, save cursor pos
300 // Ideally, the whole cursor stack should be saved, but session
301 // currently can only handle bottom (whole document) level pit and pos.
302 // That is to say, if a cursor is in a nested inset, it will be
303 // restore to the left of the top level inset.
304 LastFilePosSection::FilePos fp;
305 fp.pit = d->cursor_.bottom().pit();
306 fp.pos = d->cursor_.bottom().pos();
307 theSession().lastFilePos().save(buffer_.fileName(), fp);
313 int BufferView::rightMargin() const
315 // The additional test for the case the outliner is opened.
317 !lyxrc.full_screen_limit ||
318 width_ < lyxrc.full_screen_width + 20)
321 return (width_ - lyxrc.full_screen_width) / 2;
325 int BufferView::leftMargin() const
327 return rightMargin();
331 bool BufferView::isTopScreen() const
333 return d->scrollbarParameters_.position == d->scrollbarParameters_.min;
337 bool BufferView::isBottomScreen() const
339 return d->scrollbarParameters_.position == d->scrollbarParameters_.max;
343 Intl & BufferView::getIntl()
349 Intl const & BufferView::getIntl() const
355 CoordCache & BufferView::coordCache()
357 return d->coord_cache_;
361 CoordCache const & BufferView::coordCache() const
363 return d->coord_cache_;
367 Buffer & BufferView::buffer()
373 Buffer const & BufferView::buffer() const
379 bool BufferView::fitCursor()
381 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
382 frontend::FontMetrics const & fm =
383 theFontMetrics(d->cursor_.getFont().fontInfo());
384 int const asc = fm.maxAscent();
385 int const des = fm.maxDescent();
386 Point const p = getPos(d->cursor_, d->cursor_.boundary());
387 if (p.y_ - asc >= 0 && p.y_ + des < height_)
394 void BufferView::processUpdateFlags(Update::flags flags)
396 // last_inset_ points to the last visited inset. This pointer may become
397 // invalid because of keyboard editing. Since all such operations
398 // causes screen update(), I reset last_inset_ to avoid such a problem.
400 // This is close to a hot-path.
401 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
402 << "[fitcursor = " << (flags & Update::FitCursor)
403 << ", forceupdate = " << (flags & Update::Force)
404 << ", singlepar = " << (flags & Update::SinglePar)
405 << "] buffer: " << &buffer_);
407 buffer_.updateMacros();
409 // Now do the first drawing step if needed. This consists on updating
410 // the CoordCache in updateMetrics().
411 // The second drawing step is done in WorkArea::redraw() if needed.
413 // Case when no explicit update is requested.
415 // no need to redraw anything.
416 d->update_strategy_ = NoScreenUpdate;
420 if (flags == Update::Decoration) {
421 d->update_strategy_ = DecorationUpdate;
426 if (flags == Update::FitCursor
427 || flags == (Update::Decoration | Update::FitCursor)) {
428 // tell the frontend to update the screen if needed.
433 if (flags & Update::Decoration) {
434 d->update_strategy_ = DecorationUpdate;
438 // no screen update is needed.
439 d->update_strategy_ = NoScreenUpdate;
443 bool const full_metrics = flags & Update::Force || !singleParUpdate();
446 // We have to update the full screen metrics.
449 if (!(flags & Update::FitCursor)) {
450 // Nothing to do anymore. Trigger a redraw and return
455 // updateMetrics() does not update paragraph position
456 // This is done at draw() time. So we need a redraw!
460 // The cursor is off screen so ensure it is visible.
467 void BufferView::updateScrollbar()
469 if (height_ == 0 && width_ == 0)
472 // We prefer fixed size line scrolling.
473 d->scrollbarParameters_.single_step = defaultRowHeight();
474 // We prefer full screen page scrolling.
475 d->scrollbarParameters_.page_step = height_;
477 Text & t = buffer_.text();
478 TextMetrics & tm = d->text_metrics_[&t];
480 LYXERR(Debug::GUI, " Updating scrollbar: height: "
481 << t.paragraphs().size()
482 << " curr par: " << d->cursor_.bottom().pit()
483 << " default height " << defaultRowHeight());
485 size_t const parsize = t.paragraphs().size();
486 if (d->par_height_.size() != parsize) {
487 d->par_height_.clear();
488 // FIXME: We assume a default paragraph height of 2 rows. This
489 // should probably be pondered with the screen width.
490 d->par_height_.resize(parsize, defaultRowHeight() * 2);
493 // Look at paragraph heights on-screen
494 pair<pit_type, ParagraphMetrics const *> first = tm.first();
495 pair<pit_type, ParagraphMetrics const *> last = tm.last();
496 for (pit_type pit = first.first; pit <= last.first; ++pit) {
497 d->par_height_[pit] = tm.parMetrics(pit).height();
498 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
499 << d->par_height_[pit]);
502 int top_pos = first.second->position() - first.second->ascent();
503 int bottom_pos = last.second->position() + last.second->descent();
504 bool first_visible = first.first == 0 && top_pos >= 0;
505 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
506 if (first_visible && last_visible) {
507 d->scrollbarParameters_.min = 0;
508 d->scrollbarParameters_.max = 0;
512 d->scrollbarParameters_.min = top_pos;
513 for (size_t i = 0; i != size_t(first.first); ++i)
514 d->scrollbarParameters_.min -= d->par_height_[i];
515 d->scrollbarParameters_.max = bottom_pos;
516 for (size_t i = last.first + 1; i != parsize; ++i)
517 d->scrollbarParameters_.max += d->par_height_[i];
519 d->scrollbarParameters_.position = 0;
520 // The reference is the top position so we remove one page.
521 if (lyxrc.scroll_below_document)
522 d->scrollbarParameters_.max -= minVisiblePart();
524 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
528 ScrollbarParameters const & BufferView::scrollbarParameters() const
530 return d->scrollbarParameters_;
534 docstring BufferView::toolTip(int x, int y) const
536 // Get inset under mouse, if there is one.
537 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
539 // No inset, no tooltip...
541 return covering_inset->toolTip(*this, x, y);
545 docstring BufferView::contextMenu(int x, int y) const
547 //If there is a selection, return the containing inset menu
548 if (d->cursor_.selection())
549 return d->cursor_.inset().contextMenu(*this, x, y);
551 // Get inset under mouse, if there is one.
552 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
554 return covering_inset->contextMenu(*this, x, y);
556 return buffer_.inset().contextMenu(*this, x, y);
560 void BufferView::scrollDocView(int value)
562 int const offset = value - d->scrollbarParameters_.position;
564 // No scrolling at all? No need to redraw anything
568 // If the offset is less than 2 screen height, prefer to scroll instead.
569 if (abs(offset) <= 2 * height_) {
570 d->anchor_ypos_ -= offset;
576 // cut off at the top
577 if (value <= d->scrollbarParameters_.min) {
578 DocIterator dit = doc_iterator_begin(&buffer_);
580 LYXERR(Debug::SCROLLING, "scroll to top");
584 // cut off at the bottom
585 if (value >= d->scrollbarParameters_.max) {
586 DocIterator dit = doc_iterator_end(&buffer_);
589 LYXERR(Debug::SCROLLING, "scroll to bottom");
593 // find paragraph at target position
594 int par_pos = d->scrollbarParameters_.min;
596 for (; i != int(d->par_height_.size()); ++i) {
597 par_pos += d->par_height_[i];
598 if (par_pos >= value)
602 if (par_pos < value) {
603 // It seems we didn't find the correct pit so stay on the safe side and
605 LYXERR0("scrolling position not found!");
606 scrollDocView(d->scrollbarParameters_.max);
610 DocIterator dit = doc_iterator_begin(&buffer_);
612 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
617 // FIXME: this method is not working well.
618 void BufferView::setCursorFromScrollbar()
620 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
622 int const height = 2 * defaultRowHeight();
623 int const first = height;
624 int const last = height_ - height;
626 Cursor const & oldcur = d->cursor_;
628 switch (cursorStatus(oldcur)) {
636 int const y = getPos(oldcur, oldcur.boundary()).y_;
637 newy = min(last, max(y, first));
641 // We reset the cursor because cursorStatus() does not
642 // work when the cursor is within mathed.
644 cur.reset(buffer_.inset());
645 tm.setCursorFromCoordinates(cur, 0, newy);
647 // update the bufferview cursor and notify insets
648 // FIXME: Care about the d->cursor_ flags to redraw if needed
649 Cursor old = d->cursor_;
651 bool badcursor = notifyCursorLeavesOrEnters(old, d->cursor_);
653 d->cursor_.fixIfBroken();
657 Change const BufferView::getCurrentChange() const
659 if (!d->cursor_.selection())
660 return Change(Change::UNCHANGED);
662 DocIterator dit = d->cursor_.selectionBegin();
663 return dit.paragraph().lookupChange(dit.pos());
667 // this could be used elsewhere as well?
668 // FIXME: This does not work within mathed!
669 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
671 Point const p = getPos(dit, dit.boundary());
674 if (p.y_ > workHeight())
680 void BufferView::bookmarkEditPosition()
682 // Don't eat cpu time for each keystroke
683 if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
686 d->bookmark_edit_position_ = d->cursor_.paragraph().id();
690 void BufferView::saveBookmark(unsigned int idx)
692 // tentatively save bookmark, id and pos will be used to
693 // acturately locate a bookmark in a 'live' lyx session.
694 // pit and pos will be updated with bottom level pit/pos
696 theSession().bookmarks().save(
698 d->cursor_.bottom().pit(),
699 d->cursor_.bottom().pos(),
700 d->cursor_.paragraph().id(),
705 // emit message signal.
706 message(_("Save bookmark"));
710 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
711 int top_id, pos_type top_pos)
713 bool success = false;
716 d->cursor_.clearSelection();
718 // if a valid par_id is given, try it first
719 // This is the case for a 'live' bookmark when unique paragraph ID
720 // is used to track bookmarks.
722 dit = buffer_.getParFromID(top_id);
724 dit.pos() = min(dit.paragraph().size(), top_pos);
725 // Some slices of the iterator may not be
726 // reachable (e.g. closed collapsable inset)
727 // so the dociterator may need to be
728 // shortened. Otherwise, setCursor may crash
729 // lyx when the cursor can not be set to these
731 size_t const n = dit.depth();
732 for (size_t i = 0; i < n; ++i)
733 if (!dit[i].inset().editable()) {
741 // if top_id == 0, or searching through top_id failed
742 // This is the case for a 'restored' bookmark when only bottom
743 // (document level) pit was saved. Because of this, bookmark
744 // restoration is inaccurate. If a bookmark was within an inset,
745 // it will be restored to the left of the outmost inset that contains
747 if (bottom_pit < int(buffer_.paragraphs().size())) {
748 dit = doc_iterator_begin(&buffer_);
750 dit.pit() = bottom_pit;
751 dit.pos() = min(bottom_pos, dit.paragraph().size());
756 // Note: only bottom (document) level pit is set.
758 // set the current font.
759 d->cursor_.setCurrentFont();
760 // To center the screen on this new position we need the
761 // paragraph position which is computed at draw() time.
762 // So we need a redraw!
772 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
774 if (lyxrc.rtl_support) {
775 if (d->cursor_.real_current_font.isRightToLeft()) {
776 if (d->intl_.keymap == Intl::PRIMARY)
777 d->intl_.keyMapSec();
779 if (d->intl_.keymap == Intl::SECONDARY)
780 d->intl_.keyMapPrim();
784 d->intl_.getTransManager().translateAndInsert(c, t, cur);
788 int BufferView::workWidth() const
794 void BufferView::recenter()
796 showCursor(d->cursor_, true);
800 void BufferView::showCursor()
802 showCursor(d->cursor_, false);
806 void BufferView::showCursor(DocIterator const & dit, bool recenter)
808 if (scrollToCursor(dit, recenter))
813 void BufferView::scrollToCursor()
815 scrollToCursor(d->cursor_, false);
819 bool BufferView::scrollToCursor(DocIterator const & dit, bool recenter)
821 // We are not properly started yet, delay until resizing is
826 LYXERR(Debug::SCROLLING, "recentering!");
828 CursorSlice const & bot = dit.bottom();
829 TextMetrics & tm = d->text_metrics_[bot.text()];
831 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
832 int bot_pit = bot.pit();
833 if (bot_pit > max_pit) {
834 // FIXME: Why does this happen?
835 LYXERR0("bottom pit is greater that max pit: "
836 << bot_pit << " > " << max_pit);
840 if (bot_pit == tm.first().first - 1)
841 tm.newParMetricsUp();
842 else if (bot_pit == tm.last().first + 1)
843 tm.newParMetricsDown();
845 if (tm.contains(bot_pit)) {
846 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
847 LASSERT(!pm.rows().empty(), /**/);
848 // FIXME: smooth scrolling doesn't work in mathed.
849 CursorSlice const & cs = dit.innerTextSlice();
850 int offset = coordOffset(dit, dit.boundary()).y_;
851 int ypos = pm.position() + offset;
852 Dimension const & row_dim =
853 pm.getRow(cs.pos(), dit.boundary()).dimension();
856 scrolled = scroll(ypos - height_/2);
857 else if (ypos - row_dim.ascent() < 0)
858 scrolled = scrollUp(- ypos + row_dim.ascent());
859 else if (ypos + row_dim.descent() > height_)
860 scrolled = scrollDown(ypos - height_ + defaultRowHeight() );
862 // else, nothing to do, the cursor is already visible so we just return.
870 // fix inline completion position
871 if (d->inlineCompletionPos_.fixIfBroken())
872 d->inlineCompletionPos_ = DocIterator();
874 tm.redoParagraph(bot_pit);
875 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
876 int offset = coordOffset(dit, dit.boundary()).y_;
878 d->anchor_pit_ = bot_pit;
879 CursorSlice const & cs = dit.innerTextSlice();
880 Dimension const & row_dim =
881 pm.getRow(cs.pos(), dit.boundary()).dimension();
884 d->anchor_ypos_ = height_/2;
885 else if (d->anchor_pit_ == 0)
886 d->anchor_ypos_ = offset + pm.ascent();
887 else if (d->anchor_pit_ == max_pit)
888 d->anchor_ypos_ = height_ - offset - row_dim.descent();
889 else if (offset > height_)
890 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
892 d->anchor_ypos_ = defaultRowHeight() * 2;
899 void BufferView::updateLayout(DocumentClass const * const oldlayout)
901 message(_("Converting document to new document class..."));
903 StableDocIterator backcur(d->cursor_);
904 ErrorList & el = buffer_.errorList("Class Switch");
905 cap::switchBetweenClasses(
906 oldlayout, buffer_.params().documentClassPtr(),
907 static_cast<InsetText &>(buffer_.inset()), el);
909 setCursor(backcur.asDocIterator(&buffer_));
911 buffer_.errors("Class Switch");
912 buffer_.updateLabels();
916 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
918 Cursor & cur = d->cursor_;
920 switch (cmd.action) {
922 // FIXME: This is a bit problematic because we don't check is this is a
923 // document BufferView or not for these LFUNs. We probably have to
924 // dispatch both to currentBufferView() and, if that fails,
925 // to documentBufferView(); same as we do know for current Buffer and
926 // document Buffer. Ideally those LFUN should go to Buffer as they*
927 // operate on the full Buffer and the cursor is only needed either for
928 // an Undo record or to restore a cursor position. But we don't know
929 // how to do that inside Buffer of course.
930 case LFUN_BUFFER_PARAMS_APPLY:
931 case LFUN_LAYOUT_MODULES_CLEAR:
932 case LFUN_LAYOUT_MODULE_ADD:
933 case LFUN_LAYOUT_RELOAD:
934 case LFUN_TEXTCLASS_APPLY:
935 case LFUN_TEXTCLASS_LOAD:
936 flag.setEnabled(!buffer_.isReadonly());
940 flag.setEnabled(buffer_.undo().hasUndoStack());
943 flag.setEnabled(buffer_.undo().hasRedoStack());
945 case LFUN_FILE_INSERT:
946 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
947 case LFUN_FILE_INSERT_PLAINTEXT:
948 case LFUN_BOOKMARK_SAVE:
949 // FIXME: Actually, these LFUNS should be moved to Text
950 flag.setEnabled(cur.inTexted());
953 case LFUN_FONT_STATE:
954 case LFUN_LABEL_INSERT:
955 case LFUN_INFO_INSERT:
956 case LFUN_INSET_EDIT:
957 case LFUN_PARAGRAPH_GOTO:
959 case LFUN_REFERENCE_NEXT:
961 case LFUN_WORD_FIND_FORWARD:
962 case LFUN_WORD_FIND_BACKWARD:
963 case LFUN_WORD_FINDADV:
964 case LFUN_WORD_REPLACE:
967 case LFUN_MARK_TOGGLE:
968 case LFUN_SCREEN_RECENTER:
969 case LFUN_SCREEN_SHOW_CURSOR:
970 case LFUN_BIBTEX_DATABASE_ADD:
971 case LFUN_BIBTEX_DATABASE_DEL:
972 case LFUN_NOTES_MUTATE:
973 case LFUN_ALL_INSETS_TOGGLE:
974 case LFUN_STATISTICS:
975 case LFUN_BRANCH_ADD_INSERT:
976 case LFUN_KEYMAP_OFF:
977 case LFUN_KEYMAP_PRIMARY:
978 case LFUN_KEYMAP_SECONDARY:
979 case LFUN_KEYMAP_TOGGLE:
980 flag.setEnabled(true);
983 case LFUN_REGEXP_MODE:
984 // FIXME: Test if current WorkArea is the search WorkArea
985 flag.setEnabled(buffer().isInternal() && !cur.inRegexped());
988 case LFUN_LABEL_COPY_AS_REF: {
989 // if there is an inset at cursor, see whether it
991 Inset * inset = cur.nextInset();
992 if (!inset || !inset->getStatus(cur, cmd, flag))
993 flag.setEnabled(false);
997 case LFUN_NEXT_INSET_MODIFY: {
998 // this is the real function we want to invoke
999 FuncRequest tmpcmd = cmd;
1000 tmpcmd.action = LFUN_INSET_MODIFY;
1001 // if there is an inset at cursor, see whether it
1002 // handles the lfun, other start from scratch
1003 Inset * inset = cur.nextInset();
1004 if (!inset || !inset->getStatus(cur, tmpcmd, flag))
1005 flag = lyx::getStatus(tmpcmd);
1009 case LFUN_LABEL_GOTO: {
1010 flag.setEnabled(!cmd.argument().empty()
1011 || getInsetByCode<InsetRef>(cur, REF_CODE));
1015 case LFUN_CHANGES_TRACK:
1016 flag.setEnabled(true);
1017 flag.setOnOff(buffer_.params().trackChanges);
1020 case LFUN_CHANGES_OUTPUT:
1021 flag.setEnabled(true);
1022 flag.setOnOff(buffer_.params().outputChanges);
1025 case LFUN_CHANGES_MERGE:
1026 case LFUN_CHANGE_NEXT:
1027 case LFUN_CHANGE_PREVIOUS:
1028 case LFUN_ALL_CHANGES_ACCEPT:
1029 case LFUN_ALL_CHANGES_REJECT:
1030 // TODO: context-sensitive enabling of LFUNs
1031 // In principle, these command should only be enabled if there
1032 // is a change in the document. However, without proper
1033 // optimizations, this will inevitably result in poor performance.
1034 flag.setEnabled(true);
1037 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
1038 flag.setOnOff(buffer_.params().compressed);
1042 case LFUN_SCREEN_UP:
1043 case LFUN_SCREEN_DOWN:
1045 case LFUN_SCREEN_UP_SELECT:
1046 case LFUN_SCREEN_DOWN_SELECT:
1047 flag.setEnabled(true);
1050 case LFUN_LAYOUT_TABULAR:
1051 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1055 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1058 case LFUN_LAYOUT_PARAGRAPH:
1059 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1062 case LFUN_DIALOG_SHOW_NEW_INSET:
1063 // FIXME: this is wrong, but I do not understand the
1065 if (cur.inset().lyxCode() == CAPTION_CODE)
1066 return cur.inset().getStatus(cur, cmd, flag);
1067 // FIXME we should consider passthru paragraphs too.
1068 flag.setEnabled(!cur.inset().getLayout().isPassThru());
1072 flag.setEnabled(false);
1080 bool BufferView::dispatch(FuncRequest const & cmd)
1082 //lyxerr << [ cmd = " << cmd << "]" << endl;
1084 // Make sure that the cached BufferView is correct.
1085 LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
1086 << " arg[" << to_utf8(cmd.argument()) << ']'
1087 << " x[" << cmd.x << ']'
1088 << " y[" << cmd.y << ']'
1089 << " button[" << cmd.button() << ']');
1091 string const argument = to_utf8(cmd.argument());
1092 Cursor & cur = d->cursor_;
1094 switch (cmd.action) {
1096 case LFUN_BUFFER_PARAMS_APPLY: {
1097 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1098 cur.recordUndoFullDocument();
1099 istringstream ss(to_utf8(cmd.argument()));
1102 int const unknown_tokens = buffer_.readHeader(lex);
1103 if (unknown_tokens != 0) {
1104 LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1105 << unknown_tokens << " unknown token"
1106 << (unknown_tokens == 1 ? "" : "s"));
1108 updateLayout(oldClass);
1110 // We are most certainly here because of a change in the document
1111 // It is then better to make sure that all dialogs are in sync with
1112 // current document settings.
1113 processUpdateFlags(Update::Force | Update::FitCursor);
1117 case LFUN_LAYOUT_MODULES_CLEAR: {
1118 DocumentClass const * const oldClass =
1119 buffer_.params().documentClassPtr();
1120 cur.recordUndoFullDocument();
1121 buffer_.params().clearLayoutModules();
1122 buffer_.params().makeDocumentClass();
1123 updateLayout(oldClass);
1124 processUpdateFlags(Update::Force | Update::FitCursor);
1128 case LFUN_LAYOUT_MODULE_ADD: {
1129 BufferParams const & params = buffer_.params();
1130 if (!params.moduleCanBeAdded(argument)) {
1131 LYXERR0("Module `" << argument <<
1132 "' cannot be added due to failed requirements or "
1133 "conflicts with installed modules.");
1136 DocumentClass const * const oldClass = params.documentClassPtr();
1137 cur.recordUndoFullDocument();
1138 buffer_.params().addLayoutModule(argument);
1139 buffer_.params().makeDocumentClass();
1140 updateLayout(oldClass);
1141 processUpdateFlags(Update::Force | Update::FitCursor);
1145 case LFUN_TEXTCLASS_APPLY: {
1146 if (!LayoutFileList::get().load(argument, buffer_.temppath()) &&
1147 !LayoutFileList::get().load(argument, buffer_.filePath()))
1150 LayoutFile const * old_layout = buffer_.params().baseClass();
1151 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1153 if (old_layout == new_layout)
1157 //Save the old, possibly modular, layout for use in conversion.
1158 DocumentClass const * const oldDocClass =
1159 buffer_.params().documentClassPtr();
1160 cur.recordUndoFullDocument();
1161 buffer_.params().setBaseClass(argument);
1162 buffer_.params().makeDocumentClass();
1163 updateLayout(oldDocClass);
1164 processUpdateFlags(Update::Force | Update::FitCursor);
1168 case LFUN_TEXTCLASS_LOAD:
1169 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1170 LayoutFileList::get().load(argument, buffer_.filePath());
1173 case LFUN_LAYOUT_RELOAD: {
1174 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1175 LayoutFileIndex bc = buffer_.params().baseClassID();
1176 LayoutFileList::get().reset(bc);
1177 buffer_.params().setBaseClass(bc);
1178 buffer_.params().makeDocumentClass();
1179 updateLayout(oldClass);
1180 processUpdateFlags(Update::Force | Update::FitCursor);
1185 cur.message(_("Undo"));
1186 cur.clearSelection();
1187 if (!cur.textUndo())
1188 cur.message(_("No further undo information"));
1190 processUpdateFlags(Update::Force | Update::FitCursor);
1194 cur.message(_("Redo"));
1195 cur.clearSelection();
1196 if (!cur.textRedo())
1197 cur.message(_("No further redo information"));
1199 processUpdateFlags(Update::Force | Update::FitCursor);
1202 case LFUN_FONT_STATE:
1203 cur.message(cur.currentState());
1206 case LFUN_BOOKMARK_SAVE:
1207 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1210 case LFUN_LABEL_GOTO: {
1211 docstring label = cmd.argument();
1212 if (label.empty()) {
1214 getInsetByCode<InsetRef>(cur, REF_CODE);
1216 label = inset->getParam("reference");
1217 // persistent=false: use temp_bookmark
1226 case LFUN_INSET_EDIT: {
1227 FuncRequest fr(cmd);
1228 // if there is an inset at cursor, see whether it
1230 Inset * inset = cur.nextInset();
1232 inset->dispatch(cur, fr);
1233 // if it did not work, try the underlying inset.
1234 if (!inset || !cur.result().dispatched())
1237 // FIXME I'm adding the last break to solve a crash,
1238 // but that is obviously not right.
1239 if (!cur.result().dispatched())
1240 // It did not work too; no action needed.
1245 case LFUN_PARAGRAPH_GOTO: {
1246 int const id = convert<int>(cmd.getArg(0));
1247 int const pos = convert<int>(cmd.getArg(1));
1249 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1250 b = theBufferList().next(b)) {
1252 DocIterator dit = b->getParFromID(id);
1254 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1258 LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1259 << " found in buffer `"
1260 << b->absFileName() << "'.");
1262 if (b == &buffer_) {
1266 processUpdateFlags(Update::Force | Update::FitCursor);
1268 // Switch to other buffer view and resend cmd
1269 theLyXFunc().dispatch(FuncRequest(
1270 LFUN_BUFFER_SWITCH, b->absFileName()));
1271 theLyXFunc().dispatch(cmd);
1278 case LFUN_NOTE_NEXT:
1279 gotoInset(this, NOTE_CODE, false);
1282 case LFUN_REFERENCE_NEXT: {
1283 vector<InsetCode> tmp;
1284 tmp.push_back(LABEL_CODE);
1285 tmp.push_back(REF_CODE);
1286 gotoInset(this, tmp, true);
1290 case LFUN_CHANGES_TRACK:
1291 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1294 case LFUN_CHANGES_OUTPUT:
1295 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1296 if (buffer_.params().outputChanges) {
1297 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1298 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1299 LaTeXFeatures::isAvailable("xcolor");
1301 if (!dvipost && !xcolorulem) {
1302 Alert::warning(_("Changes not shown in LaTeX output"),
1303 _("Changes will not be highlighted in LaTeX output, "
1304 "because neither dvipost nor xcolor/ulem are installed.\n"
1305 "Please install these packages or redefine "
1306 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1307 } else if (!xcolorulem) {
1308 Alert::warning(_("Changes not shown in LaTeX output"),
1309 _("Changes will not be highlighted in LaTeX output "
1310 "when using pdflatex, because xcolor and ulem are not installed.\n"
1311 "Please install both packages or redefine "
1312 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1317 case LFUN_CHANGE_NEXT:
1318 findNextChange(this);
1319 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1320 processUpdateFlags(Update::Force | Update::FitCursor);
1323 case LFUN_CHANGE_PREVIOUS:
1324 findPreviousChange(this);
1325 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1326 processUpdateFlags(Update::Force | Update::FitCursor);
1329 case LFUN_CHANGES_MERGE:
1330 if (findNextChange(this) || findPreviousChange(this)) {
1331 processUpdateFlags(Update::Force | Update::FitCursor);
1332 showDialog("changes");
1336 case LFUN_ALL_CHANGES_ACCEPT:
1337 // select complete document
1338 cur.reset(buffer_.inset());
1339 cur.selHandle(true);
1340 buffer_.text().cursorBottom(cur);
1341 // accept everything in a single step to support atomic undo
1342 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1343 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1344 processUpdateFlags(Update::Force | Update::FitCursor);
1347 case LFUN_ALL_CHANGES_REJECT:
1348 // select complete document
1349 cur.reset(buffer_.inset());
1350 cur.selHandle(true);
1351 buffer_.text().cursorBottom(cur);
1352 // reject everything in a single step to support atomic undo
1353 // Note: reject does not work recursively; the user may have to repeat the operation
1354 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1355 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1356 processUpdateFlags(Update::Force | Update::FitCursor);
1359 case LFUN_WORD_FIND_FORWARD:
1360 case LFUN_WORD_FIND_BACKWARD: {
1361 static docstring last_search;
1362 docstring searched_string;
1364 if (!cmd.argument().empty()) {
1365 last_search = cmd.argument();
1366 searched_string = cmd.argument();
1368 searched_string = last_search;
1371 if (searched_string.empty())
1374 bool const fw = cmd.action == LFUN_WORD_FIND_FORWARD;
1375 docstring const data =
1376 find2string(searched_string, true, false, fw);
1377 find(this, FuncRequest(LFUN_WORD_FIND, data));
1381 case LFUN_WORD_FIND: {
1382 FuncRequest req = cmd;
1383 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1384 req = d->search_request_cache_;
1385 if (req.argument().empty()) {
1386 theLyXFunc().dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1389 if (find(this, req))
1392 message(_("String not found!"));
1393 d->search_request_cache_ = req;
1397 case LFUN_WORD_REPLACE: {
1398 bool has_deleted = false;
1399 if (cur.selection()) {
1400 DocIterator beg = cur.selectionBegin();
1401 DocIterator end = cur.selectionEnd();
1402 if (beg.pit() == end.pit()) {
1403 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1404 if (cur.paragraph().isDeleted(p))
1409 replace(this, cmd, has_deleted);
1413 case LFUN_WORD_FINDADV:
1418 cur.clearSelection();
1419 cur.message(from_utf8(N_("Mark off")));
1423 cur.clearSelection();
1425 cur.message(from_utf8(N_("Mark on")));
1428 case LFUN_MARK_TOGGLE:
1429 cur.setSelection(false);
1432 cur.message(from_utf8(N_("Mark removed")));
1435 cur.message(from_utf8(N_("Mark set")));
1440 case LFUN_SCREEN_SHOW_CURSOR:
1444 case LFUN_SCREEN_RECENTER:
1448 case LFUN_BIBTEX_DATABASE_ADD: {
1449 Cursor tmpcur = cur;
1450 findInset(tmpcur, BIBTEX_CODE, false);
1451 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1454 if (inset->addDatabase(cmd.argument()))
1455 buffer_.updateBibfilesCache();
1460 case LFUN_BIBTEX_DATABASE_DEL: {
1461 Cursor tmpcur = cur;
1462 findInset(tmpcur, BIBTEX_CODE, false);
1463 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1466 if (inset->delDatabase(cmd.argument()))
1467 buffer_.updateBibfilesCache();
1472 case LFUN_STATISTICS: {
1473 DocIterator from, to;
1474 if (cur.selection()) {
1475 from = cur.selectionBegin();
1476 to = cur.selectionEnd();
1478 from = doc_iterator_begin(&buffer_);
1479 to = doc_iterator_end(&buffer_);
1481 int const words = countWords(from, to);
1482 int const chars = countChars(from, to, false);
1483 int const chars_blanks = countChars(from, to, true);
1485 if (cur.selection())
1486 message = _("Statistics for the selection:");
1488 message = _("Statistics for the document:");
1491 message += bformat(_("%1$d words"), words);
1493 message += _("One word");
1495 if (chars_blanks != 1)
1496 message += bformat(_("%1$d characters (including blanks)"),
1499 message += _("One character (including blanks)");
1502 message += bformat(_("%1$d characters (excluding blanks)"),
1505 message += _("One character (excluding blanks)");
1507 Alert::information(_("Statistics"), message);
1511 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1512 // turn compression on/off
1513 buffer_.params().compressed = !buffer_.params().compressed;
1516 case LFUN_LABEL_COPY_AS_REF: {
1517 // if there is an inset at cursor, try to copy it
1518 Inset * inset = &cur.inset();
1519 if (!inset || !inset->asInsetMath())
1520 inset = cur.nextInset();
1522 FuncRequest tmpcmd = cmd;
1523 inset->dispatch(cur, tmpcmd);
1525 if (!cur.result().dispatched())
1526 // It did not work too; no action needed.
1528 cur.clearSelection();
1529 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1533 case LFUN_NEXT_INSET_MODIFY: {
1534 // create the the real function we want to invoke
1535 FuncRequest tmpcmd = cmd;
1536 tmpcmd.action = LFUN_INSET_MODIFY;
1537 // if there is an inset at cursor, see whether it
1539 Inset * inset = cur.nextInset();
1542 inset->dispatch(cur, tmpcmd);
1544 // if it did not work, try the underlying inset.
1545 if (!inset || !cur.result().dispatched()) {
1547 cur.dispatch(tmpcmd);
1550 if (!cur.result().dispatched())
1551 // It did not work too; no action needed.
1553 cur.clearSelection();
1554 processUpdateFlags(Update::Force | Update::FitCursor);
1558 case LFUN_SCREEN_UP:
1559 case LFUN_SCREEN_DOWN: {
1560 Point p = getPos(cur, cur.boundary());
1561 // This code has been commented out to enable to scroll down a
1562 // document, even if there are large insets in it (see bug #5465).
1563 /*if (p.y_ < 0 || p.y_ > height_) {
1564 // The cursor is off-screen so recenter before proceeding.
1566 p = getPos(cur, cur.boundary());
1568 int const scrolled = scroll(cmd.action == LFUN_SCREEN_UP
1569 ? -height_ : height_);
1570 if (cmd.action == LFUN_SCREEN_UP && scrolled > -height_)
1572 if (cmd.action == LFUN_SCREEN_DOWN && scrolled < height_)
1573 p = Point(width_, height_);
1575 bool const in_texted = cur.inTexted();
1576 cur.reset(buffer_.inset());
1579 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1580 true, cmd.action == LFUN_SCREEN_UP);
1581 //FIXME: what to do with cur.x_target()?
1582 bool update = in_texted && cur.bv().checkDepm(cur, old);
1585 processUpdateFlags(Update::Force | Update::FitCursor);
1593 case LFUN_SCREEN_UP_SELECT: {
1594 cur.selHandle(true);
1595 if (isTopScreen()) {
1596 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1600 int y = getPos(cur, cur.boundary()).y_;
1601 int const ymin = y - height_ + defaultRowHeight();
1602 while (y > ymin && cur.up())
1603 y = getPos(cur, cur.boundary()).y_;
1606 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1610 case LFUN_SCREEN_DOWN_SELECT: {
1611 cur.selHandle(true);
1612 if (isBottomScreen()) {
1613 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1617 int y = getPos(cur, cur.boundary()).y_;
1618 int const ymax = y + height_ - defaultRowHeight();
1619 while (y < ymax && cur.down())
1620 y = getPos(cur, cur.boundary()).y_;
1623 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1627 // This could be rewriten using some command like forall <insetname> <command>
1628 // once the insets refactoring is done.
1629 case LFUN_NOTES_MUTATE: {
1630 if (cmd.argument().empty())
1633 if (mutateNotes(cur, cmd.getArg(0), cmd.getArg(1))) {
1634 processUpdateFlags(Update::Force);
1639 case LFUN_ALL_INSETS_TOGGLE: {
1641 string const name = split(to_utf8(cmd.argument()), action, ' ');
1642 InsetCode const inset_code = insetCode(name);
1644 FuncRequest fr(LFUN_INSET_TOGGLE, action);
1646 Inset & inset = cur.buffer()->inset();
1647 InsetIterator it = inset_iterator_begin(inset);
1648 InsetIterator const end = inset_iterator_end(inset);
1649 for (; it != end; ++it) {
1650 if (it->asInsetCollapsable()
1651 && (inset_code == NO_CODE
1652 || inset_code == it->lyxCode())) {
1653 Cursor tmpcur = cur;
1654 tmpcur.pushBackward(*it);
1655 it->dispatch(tmpcur, fr);
1658 processUpdateFlags(Update::Force | Update::FitCursor);
1662 case LFUN_BRANCH_ADD_INSERT: {
1663 docstring branch_name = from_utf8(cmd.getArg(0));
1664 if (branch_name.empty())
1665 if (!Alert::askForText(branch_name, _("Branch name")) ||
1666 branch_name.empty())
1669 DispatchResult drtmp;
1670 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
1671 if (drtmp.error()) {
1672 Alert::warning(_("Branch already exists"), drtmp.message());
1675 BranchList & branch_list = buffer_.params().branchlist();
1676 Branch const * branch = branch_list.find(branch_name);
1677 string const x11hexname = X11hexname(branch->color());
1678 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
1679 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
1680 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch_name));
1684 case LFUN_KEYMAP_OFF:
1685 getIntl().keyMapOn(false);
1688 case LFUN_KEYMAP_PRIMARY:
1689 getIntl().keyMapPrim();
1692 case LFUN_KEYMAP_SECONDARY:
1693 getIntl().keyMapSec();
1696 case LFUN_KEYMAP_TOGGLE:
1697 getIntl().toggleKeyMap();
1708 docstring const BufferView::requestSelection()
1710 Cursor & cur = d->cursor_;
1712 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
1713 if (!cur.selection()) {
1714 d->xsel_cache_.set = false;
1718 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
1719 if (!d->xsel_cache_.set ||
1720 cur.top() != d->xsel_cache_.cursor ||
1721 cur.anchor_.top() != d->xsel_cache_.anchor)
1723 d->xsel_cache_.cursor = cur.top();
1724 d->xsel_cache_.anchor = cur.anchor_.top();
1725 d->xsel_cache_.set = cur.selection();
1726 return cur.selectionAsString(false);
1732 void BufferView::clearSelection()
1734 d->cursor_.clearSelection();
1735 // Clear the selection buffer. Otherwise a subsequent
1736 // middle-mouse-button paste would use the selection buffer,
1737 // not the more current external selection.
1738 cap::clearSelection();
1739 d->xsel_cache_.set = false;
1740 // The buffer did not really change, but this causes the
1741 // redraw we need because we cleared the selection above.
1746 void BufferView::resize(int width, int height)
1748 // Update from work area
1752 // Clear the paragraph height cache.
1753 d->par_height_.clear();
1754 // Redo the metrics.
1759 Inset const * BufferView::getCoveringInset(Text const & text,
1762 TextMetrics & tm = d->text_metrics_[&text];
1763 Inset * inset = tm.checkInsetHit(x, y);
1767 if (!inset->descendable())
1768 // No need to go further down if the inset is not
1772 size_t cell_number = inset->nargs();
1773 // Check all the inner cell.
1774 for (size_t i = 0; i != cell_number; ++i) {
1775 Text const * inner_text = inset->getText(i);
1778 Inset const * inset_deeper =
1779 getCoveringInset(*inner_text, x, y);
1781 return inset_deeper;
1789 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1791 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1793 // This is only called for mouse related events including
1794 // LFUN_FILE_OPEN generated by drag-and-drop.
1795 FuncRequest cmd = cmd0;
1797 Cursor old = cursor();
1799 cur.push(buffer_.inset());
1800 cur.setSelection(d->cursor_.selection());
1802 // Either the inset under the cursor or the
1803 // surrounding Text will handle this event.
1805 // make sure we stay within the screen...
1806 cmd.y = min(max(cmd.y, -1), height_);
1808 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1810 // Get inset under mouse, if there is one.
1811 Inset const * covering_inset =
1812 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1813 if (covering_inset == d->last_inset_)
1814 // Same inset, no need to do anything...
1817 bool need_redraw = false;
1818 // const_cast because of setMouseHover().
1819 Inset * inset = const_cast<Inset *>(covering_inset);
1821 // Remove the hint on the last hovered inset (if any).
1822 need_redraw |= d->last_inset_->setMouseHover(false);
1824 // Highlighted the newly hovered inset (if any).
1825 need_redraw |= inset->setMouseHover(true);
1826 d->last_inset_ = inset;
1830 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1831 << cmd.x << ", " << cmd.y << ")");
1833 d->update_strategy_ = DecorationUpdate;
1835 // This event (moving without mouse click) is not passed further.
1836 // This should be changed if it is further utilized.
1841 // Build temporary cursor.
1842 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1844 // Put anchor at the same position.
1847 cur.beginUndoGroup();
1849 // Try to dispatch to an non-editable inset near this position
1850 // via the temp cursor. If the inset wishes to change the real
1851 // cursor it has to do so explicitly by using
1852 // cur.bv().cursor() = cur; (or similar)
1854 inset->dispatch(cur, cmd);
1856 // Now dispatch to the temporary cursor. If the real cursor should
1857 // be modified, the inset's dispatch has to do so explicitly.
1858 if (!inset || !cur.result().dispatched())
1863 // Notify left insets
1866 bool badcursor = notifyCursorLeavesOrEnters(old, cur);
1868 cursor().fixIfBroken();
1871 // Do we have a selection?
1872 theSelection().haveSelection(cursor().selection());
1874 // If the command has been dispatched,
1875 if (cur.result().dispatched() || cur.result().update())
1876 processUpdateFlags(cur.result().update());
1880 void BufferView::lfunScroll(FuncRequest const & cmd)
1882 string const scroll_type = cmd.getArg(0);
1883 int const scroll_step =
1884 (scroll_type == "line") ? d->scrollbarParameters_.single_step
1885 : (scroll_type == "page") ? d->scrollbarParameters_.page_step : 0;
1886 if (scroll_step == 0)
1888 string const scroll_quantity = cmd.getArg(1);
1889 if (scroll_quantity == "up")
1890 scrollUp(scroll_step);
1891 else if (scroll_quantity == "down")
1892 scrollDown(scroll_step);
1894 int const scroll_value = convert<int>(scroll_quantity);
1896 scroll(scroll_step * scroll_value);
1903 int BufferView::minVisiblePart()
1905 return 2 * defaultRowHeight();
1909 int BufferView::scroll(int y)
1912 return scrollDown(y);
1914 return scrollUp(-y);
1919 int BufferView::scrollDown(int offset)
1921 Text * text = &buffer_.text();
1922 TextMetrics & tm = d->text_metrics_[text];
1923 int const ymax = height_ + offset;
1925 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1926 int bottom_pos = last.second->position() + last.second->descent();
1927 if (lyxrc.scroll_below_document)
1928 bottom_pos += height_ - minVisiblePart();
1929 if (last.first + 1 == int(text->paragraphs().size())) {
1930 if (bottom_pos <= height_)
1932 offset = min(offset, bottom_pos - height_);
1935 if (bottom_pos > ymax)
1937 tm.newParMetricsDown();
1939 d->anchor_ypos_ -= offset;
1944 int BufferView::scrollUp(int offset)
1946 Text * text = &buffer_.text();
1947 TextMetrics & tm = d->text_metrics_[text];
1948 int ymin = - offset;
1950 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1951 int top_pos = first.second->position() - first.second->ascent();
1952 if (first.first == 0) {
1955 offset = min(offset, - top_pos);
1960 tm.newParMetricsUp();
1962 d->anchor_ypos_ += offset;
1967 void BufferView::setCursorFromRow(int row)
1972 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1974 d->cursor_.reset(buffer_.inset());
1976 buffer_.text().setCursor(d->cursor_, 0, 0);
1978 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1982 bool BufferView::setCursorFromInset(Inset const * inset)
1984 // are we already there?
1985 if (cursor().nextInset() == inset)
1988 // Inset is not at cursor position. Find it in the document.
1990 cur.reset(buffer().inset());
1991 while (cur && cur.nextInset() != inset)
2002 void BufferView::gotoLabel(docstring const & label)
2004 std::vector<Buffer const *> bufs = buffer().allRelatives();
2005 std::vector<Buffer const *>::iterator it = bufs.begin();
2006 for (; it != bufs.end(); ++it) {
2007 Buffer const * buf = *it;
2010 Toc & toc = buf->tocBackend().toc("label");
2011 TocIterator toc_it = toc.begin();
2012 TocIterator end = toc.end();
2013 for (; toc_it != end; ++toc_it) {
2014 if (label == toc_it->str()) {
2015 dispatch(toc_it->action());
2023 TextMetrics const & BufferView::textMetrics(Text const * t) const
2025 return const_cast<BufferView *>(this)->textMetrics(t);
2029 TextMetrics & BufferView::textMetrics(Text const * t)
2031 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
2032 if (tmc_it == d->text_metrics_.end()) {
2033 tmc_it = d->text_metrics_.insert(
2034 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
2036 return tmc_it->second;
2040 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2043 return textMetrics(t).parMetrics(pit);
2047 int BufferView::workHeight() const
2053 void BufferView::setCursor(DocIterator const & dit)
2055 d->cursor_.reset(buffer().inset());
2056 size_t const n = dit.depth();
2057 for (size_t i = 0; i < n; ++i)
2058 dit[i].inset().edit(d->cursor_, true);
2060 d->cursor_.setCursor(dit);
2061 d->cursor_.setSelection(false);
2065 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2067 // Would be wrong to delete anything if we have a selection.
2068 if (cur.selection())
2071 bool need_anchor_change = false;
2072 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
2073 need_anchor_change);
2075 if (need_anchor_change)
2083 buffer_.updateLabels();
2091 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
2093 LASSERT(&cur.bv() == this, /**/);
2096 // this event will clear selection so we save selection for
2097 // persistent selection
2098 cap::saveSelection(cursor());
2100 // Has the cursor just left the inset?
2101 bool leftinset = (&d->cursor_.inset() != &cur.inset());
2103 d->cursor_.fixIfBroken();
2105 // FIXME: shift-mouse selection doesn't work well across insets.
2106 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
2108 // do the dEPM magic if needed
2109 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2110 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2111 // the leftinset bool would not be necessary (badcursor instead).
2112 bool update = leftinset;
2113 if (!do_selection && d->cursor_.inTexted())
2114 update |= checkDepm(cur, d->cursor_);
2115 d->cursor_.macroModeClose();
2117 d->cursor_.resetAnchor();
2118 d->cursor_.setCursor(cur);
2119 d->cursor_.boundary(cur.boundary());
2121 d->cursor_.setSelection();
2123 d->cursor_.clearSelection();
2125 d->cursor_.finishUndo();
2126 d->cursor_.setCurrentFont();
2131 void BufferView::putSelectionAt(DocIterator const & cur,
2132 int length, bool backwards)
2134 d->cursor_.clearSelection();
2140 d->cursor_.pos() += length;
2141 d->cursor_.setSelection(d->cursor_, -length);
2143 d->cursor_.setSelection(d->cursor_, length);
2145 // Ensure a redraw happens in any case because the new selection could
2146 // possibly be on the same screen as the previous selection.
2147 processUpdateFlags(Update::Force | Update::FitCursor);
2151 Cursor & BufferView::cursor()
2157 Cursor const & BufferView::cursor() const
2163 pit_type BufferView::anchor_ref() const
2165 return d->anchor_pit_;
2169 bool BufferView::singleParUpdate()
2171 Text & buftext = buffer_.text();
2172 pit_type const bottom_pit = d->cursor_.bottom().pit();
2173 TextMetrics & tm = textMetrics(&buftext);
2174 int old_height = tm.parMetrics(bottom_pit).height();
2176 // make sure inline completion pointer is ok
2177 if (d->inlineCompletionPos_.fixIfBroken())
2178 d->inlineCompletionPos_ = DocIterator();
2180 // In Single Paragraph mode, rebreak only
2181 // the (main text, not inset!) paragraph containing the cursor.
2182 // (if this paragraph contains insets etc., rebreaking will
2183 // recursively descend)
2184 tm.redoParagraph(bottom_pit);
2185 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
2186 if (pm.height() != old_height)
2187 // Paragraph height has changed so we cannot proceed to
2188 // the singlePar optimisation.
2191 d->update_strategy_ = SingleParUpdate;
2193 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2194 << " y2: " << pm.position() + pm.descent()
2195 << " pit: " << bottom_pit
2196 << " singlepar: 1");
2201 void BufferView::updateMetrics()
2203 if (height_ == 0 || width_ == 0)
2206 Text & buftext = buffer_.text();
2207 pit_type const npit = int(buftext.paragraphs().size());
2209 // Clear out the position cache in case of full screen redraw,
2210 d->coord_cache_.clear();
2212 // Clear out paragraph metrics to avoid having invalid metrics
2213 // in the cache from paragraphs not relayouted below
2214 // The complete text metrics will be redone.
2215 d->text_metrics_.clear();
2217 TextMetrics & tm = textMetrics(&buftext);
2219 // make sure inline completion pointer is ok
2220 if (d->inlineCompletionPos_.fixIfBroken())
2221 d->inlineCompletionPos_ = DocIterator();
2223 if (d->anchor_pit_ >= npit)
2224 // The anchor pit must have been deleted...
2225 d->anchor_pit_ = npit - 1;
2227 // Rebreak anchor paragraph.
2228 tm.redoParagraph(d->anchor_pit_);
2229 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2232 if (d->anchor_pit_ == 0) {
2233 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2235 // Complete buffer visible? Then it's easy.
2236 if (scrollRange == 0)
2237 d->anchor_ypos_ = anchor_pm.ascent();
2239 // FIXME: Some clever handling needed to show
2240 // the _first_ paragraph up to the top if the cursor is
2241 // in the first line.
2243 anchor_pm.setPosition(d->anchor_ypos_);
2245 LYXERR(Debug::PAINTING, "metrics: "
2246 << " anchor pit = " << d->anchor_pit_
2247 << " anchor ypos = " << d->anchor_ypos_);
2249 // Redo paragraphs above anchor if necessary.
2250 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2251 // We are now just above the anchor paragraph.
2252 pit_type pit1 = d->anchor_pit_ - 1;
2253 for (; pit1 >= 0 && y1 >= 0; --pit1) {
2254 tm.redoParagraph(pit1);
2255 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2257 // Save the paragraph position in the cache.
2262 // Redo paragraphs below the anchor if necessary.
2263 int y2 = d->anchor_ypos_ + anchor_pm.descent();
2264 // We are now just below the anchor paragraph.
2265 pit_type pit2 = d->anchor_pit_ + 1;
2266 for (; pit2 < npit && y2 <= height_; ++pit2) {
2267 tm.redoParagraph(pit2);
2268 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2270 // Save the paragraph position in the cache.
2275 LYXERR(Debug::PAINTING, "Metrics: "
2276 << " anchor pit = " << d->anchor_pit_
2277 << " anchor ypos = " << d->anchor_ypos_
2280 << " pit1 = " << pit1
2281 << " pit2 = " << pit2);
2283 d->update_strategy_ = FullScreenUpdate;
2285 if (lyxerr.debugging(Debug::WORKAREA)) {
2286 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2287 d->coord_cache_.dump();
2292 void BufferView::insertLyXFile(FileName const & fname)
2294 LASSERT(d->cursor_.inTexted(), /**/);
2296 // Get absolute path of file and add ".lyx"
2297 // to the filename if necessary
2298 FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
2300 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2301 // emit message signal.
2302 message(bformat(_("Inserting document %1$s..."), disp_fn));
2305 Buffer buf("", false);
2306 if (buf.loadLyXFile(filename)) {
2307 ErrorList & el = buffer_.errorList("Parse");
2308 // Copy the inserted document error list into the current buffer one.
2309 el = buf.errorList("Parse");
2310 buffer_.undo().recordUndo(d->cursor_);
2311 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2312 buf.params().documentClassPtr(), el);
2313 res = _("Document %1$s inserted.");
2315 res = _("Could not insert document %1$s");
2320 // emit message signal.
2321 message(bformat(res, disp_fn));
2322 buffer_.errors("Parse");
2326 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
2332 // Addup contribution of nested insets, from inside to outside,
2333 // keeping the outer paragraph for a special handling below
2334 for (size_t i = dit.depth() - 1; i >= 1; --i) {
2335 CursorSlice const & sl = dit[i];
2339 // get relative position inside sl.inset()
2340 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
2342 // Make relative position inside of the edited inset relative to sl.inset()
2346 // In case of an RTL inset, the edited inset will be positioned to the left
2349 bool boundary_i = boundary && i + 1 == dit.depth();
2350 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2355 // remember width for the case that sl.inset() is positioned in an RTL inset
2356 if (i && dit[i - 1].text()) {
2357 // If this Inset is inside a Text Inset, retrieve the Dimension
2358 // from the containing text instead of using Inset::dimension() which
2359 // might not be implemented.
2360 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2361 // elimination of Inset::dim_ cache. This coordOffset() method needs
2362 // to be rewritten in light of the new design.
2363 Dimension const & dim = parMetrics(dit[i - 1].text(),
2364 dit[i - 1].pit()).insetDimension(&sl.inset());
2367 Dimension const dim = sl.inset().dimension(*this);
2371 //lyxerr << "Cursor::getPos, i: "
2372 // << i << " x: " << xx << " y: " << y << endl;
2375 // Add contribution of initial rows of outermost paragraph
2376 CursorSlice const & sl = dit[0];
2377 TextMetrics const & tm = textMetrics(sl.text());
2378 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2379 LASSERT(!pm.rows().empty(), /**/);
2380 y -= pm.rows()[0].ascent();
2382 // FIXME: document this mess
2384 if (sl.pos() > 0 && dit.depth() == 1) {
2386 if (pos && boundary)
2388 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2389 rend = pm.pos2row(pos);
2391 rend = pm.pos2row(sl.pos());
2393 size_t rend = pm.pos2row(sl.pos());
2395 for (size_t rit = 0; rit != rend; ++rit)
2396 y += pm.rows()[rit].height();
2397 y += pm.rows()[rend].ascent();
2399 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2401 // Make relative position from the nested inset now bufferview absolute.
2402 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
2405 // In the RTL case place the nested inset at the left of the cursor in
2406 // the outer paragraph
2407 bool boundary_1 = boundary && 1 == dit.depth();
2408 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2416 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
2418 if (!paragraphVisible(dit))
2419 return Point(-1, -1);
2421 CursorSlice const & bot = dit.bottom();
2422 TextMetrics const & tm = textMetrics(bot.text());
2424 Point p = coordOffset(dit, boundary); // offset from outer paragraph
2425 p.y_ += tm.parMetrics(bot.pit()).position();
2430 bool BufferView::paragraphVisible(DocIterator const & dit) const
2432 CursorSlice const & bot = dit.bottom();
2433 TextMetrics const & tm = textMetrics(bot.text());
2435 return tm.contains(bot.pit());
2439 void BufferView::cursorPosAndHeight(Point & p, int & h) const
2441 Cursor const & cur = cursor();
2442 Font const font = cur.getFont();
2443 frontend::FontMetrics const & fm = theFontMetrics(font);
2444 int const asc = fm.maxAscent();
2445 int const des = fm.maxDescent();
2447 p = getPos(cur, cur.boundary());
2452 bool BufferView::cursorInView(Point const & p, int h) const
2454 Cursor const & cur = cursor();
2455 // does the cursor touch the screen ?
2456 if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
2462 void BufferView::draw(frontend::Painter & pain)
2464 if (height_ == 0 || width_ == 0)
2466 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2468 Text & text = buffer_.text();
2469 TextMetrics const & tm = d->text_metrics_[&text];
2470 int const y = tm.first().second->position();
2471 PainterInfo pi(this, pain);
2473 switch (d->update_strategy_) {
2475 case NoScreenUpdate:
2476 // If no screen painting is actually needed, only some the different
2477 // coordinates of insets and paragraphs needs to be updated.
2478 pi.full_repaint = true;
2479 pi.pain.setDrawingEnabled(false);
2483 case SingleParUpdate:
2484 pi.full_repaint = false;
2485 // In general, only the current row of the outermost paragraph
2486 // will be redrawn. Particular cases where selection spans
2487 // multiple paragraph are correctly detected in TextMetrics.
2491 case DecorationUpdate:
2492 // FIXME: We should also distinguish DecorationUpdate to avoid text
2493 // drawing if possible. This is not possible to do easily right now
2494 // because of the single backing pixmap.
2496 case FullScreenUpdate:
2497 // The whole screen, including insets, will be refreshed.
2498 pi.full_repaint = true;
2500 // Clear background.
2501 pain.fillRectangle(0, 0, width_, height_,
2502 pi.backgroundColor(&buffer_.inset()));
2507 // and possibly grey out below
2508 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2509 int const y2 = lastpm.second->position() + lastpm.second->descent();
2512 Color color = buffer().isInternal()
2513 ? Color_background : Color_bottomarea;
2514 pain.fillRectangle(0, y2, width_, height_ - y2, color);
2518 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
2520 // The scrollbar needs an update.
2523 // Normalize anchor for next time
2524 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2525 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2526 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2527 ParagraphMetrics const & pm = tm.parMetrics(pit);
2528 if (pm.position() + pm.descent() > 0) {
2529 d->anchor_pit_ = pit;
2530 d->anchor_ypos_ = pm.position();
2534 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2535 << " anchor ypos = " << d->anchor_ypos_);
2539 void BufferView::message(docstring const & msg)
2542 d->gui_->message(msg);
2546 void BufferView::showDialog(string const & name)
2549 d->gui_->showDialog(name, string());
2553 void BufferView::showDialog(string const & name,
2554 string const & data, Inset * inset)
2557 d->gui_->showDialog(name, data, inset);
2561 void BufferView::updateDialog(string const & name, string const & data)
2564 d->gui_->updateDialog(name, data);
2568 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2574 // FIXME: Move this out of BufferView again
2575 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2577 if (!fname.isReadableFile()) {
2578 docstring const error = from_ascii(strerror(errno));
2579 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2580 docstring const text =
2581 bformat(_("Could not read the specified document\n"
2582 "%1$s\ndue to the error: %2$s"), file, error);
2583 Alert::error(_("Could not read file"), text);
2587 if (!fname.isReadableFile()) {
2588 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2589 docstring const text =
2590 bformat(_("%1$s\n is not readable."), file);
2591 Alert::error(_("Could not open file"), text);
2595 // FIXME UNICODE: We don't know the encoding of the file
2596 docstring file_content = fname.fileContents("UTF-8");
2597 if (file_content.empty()) {
2598 Alert::error(_("Reading not UTF-8 encoded file"),
2599 _("The file is not UTF-8 encoded.\n"
2600 "It will be read as local 8Bit-encoded.\n"
2601 "If this does not give the correct result\n"
2602 "then please change the encoding of the file\n"
2603 "to UTF-8 with a program other than LyX.\n"));
2604 file_content = fname.fileContents("local8bit");
2607 return normalize_c(file_content);
2611 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2613 docstring const tmpstr = contentsOfPlaintextFile(f);
2618 Cursor & cur = cursor();
2619 cap::replaceSelection(cur);
2620 buffer_.undo().recordUndo(cur);
2622 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
2624 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
2631 docstring const & BufferView::inlineCompletion() const
2633 return d->inlineCompletion_;
2637 size_t const & BufferView::inlineCompletionUniqueChars() const
2639 return d->inlineCompletionUniqueChars_;
2643 DocIterator const & BufferView::inlineCompletionPos() const
2645 return d->inlineCompletionPos_;
2649 bool samePar(DocIterator const & a, DocIterator const & b)
2651 if (a.empty() && b.empty())
2653 if (a.empty() || b.empty())
2655 if (a.depth() != b.depth())
2657 return &a.innerParagraph() == &b.innerParagraph();
2661 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos,
2662 docstring const & completion, size_t uniqueChars)
2664 uniqueChars = min(completion.size(), uniqueChars);
2665 bool changed = d->inlineCompletion_ != completion
2666 || d->inlineCompletionUniqueChars_ != uniqueChars;
2667 bool singlePar = true;
2668 d->inlineCompletion_ = completion;
2669 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
2671 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2674 DocIterator const & old = d->inlineCompletionPos_;
2676 //lyxerr << "inlineCompletionPos changed" << std::endl;
2677 // old or pos are in another paragraph?
2678 if ((!samePar(cur, pos) && !pos.empty())
2679 || (!samePar(cur, old) && !old.empty())) {
2681 //lyxerr << "different paragraph" << std::endl;
2683 d->inlineCompletionPos_ = pos;
2688 if (singlePar && !(cur.disp_.update() & Update::Force))
2689 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
2691 cur.updateFlags(cur.disp_.update() | Update::Force);