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"
69 #include "frontends/alert.h"
70 #include "frontends/Application.h"
71 #include "frontends/Delegates.h"
72 #include "frontends/FontMetrics.h"
73 #include "frontends/NullPainter.h"
74 #include "frontends/Painter.h"
75 #include "frontends/Selection.h"
77 #include "support/convert.h"
78 #include "support/debug.h"
79 #include "support/ExceptionMessage.h"
80 #include "support/filetools.h"
81 #include "support/gettext.h"
82 #include "support/lassert.h"
83 #include "support/lstrings.h"
84 #include "support/Package.h"
85 #include "support/types.h"
95 using namespace lyx::support;
99 namespace Alert = frontend::Alert;
103 /// Return an inset of this class if it exists at the current cursor position
105 T * getInsetByCode(Cursor const & cur, InsetCode code)
107 DocIterator it = cur;
108 Inset * inset = it.nextInset();
109 if (inset && inset->lyxCode() == code)
110 return static_cast<T*>(inset);
115 /// Note that comparing contents can only be used for InsetCommand
116 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
117 docstring const & contents)
119 DocIterator tmpdit = dit;
122 Inset const * inset = tmpdit.nextInset();
124 bool const valid_code = std::find(codes.begin(), codes.end(),
125 inset->lyxCode()) != codes.end();
126 InsetCommand const * ic = inset->asInsetCommand();
127 bool const same_or_no_contents = contents.empty()
128 || (ic && (ic->getFirstNonOptParam() == contents));
130 if (valid_code && same_or_no_contents) {
135 tmpdit.forwardInset();
142 /// Looks for next inset with one of the given codes.
143 /// Note that same_content can only be used for InsetCommand
144 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
148 DocIterator tmpdit = dit;
149 tmpdit.forwardInset();
153 Inset const * inset = tmpdit.nextInset();
154 if (same_content && inset) {
155 InsetCommand const * ic = inset->asInsetCommand();
157 bool const valid_code = std::find(codes.begin(), codes.end(),
158 ic->lyxCode()) != codes.end();
160 contents = ic->getFirstNonOptParam();
164 if (!findNextInset(tmpdit, codes, contents)) {
165 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
166 Inset * inset = &tmpdit.bottom().inset();
167 tmpdit = doc_iterator_begin(&inset->buffer(), inset);
168 if (!findNextInset(tmpdit, codes, contents))
180 /// Looks for next inset with the given code
181 void findInset(DocIterator & dit, InsetCode code, bool same_content)
183 findInset(dit, vector<InsetCode>(1, code), same_content);
187 /// Moves cursor to the next inset with one of the given codes.
188 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
191 Cursor tmpcur = bv->cursor();
192 if (!findInset(tmpcur, codes, same_content)) {
193 bv->cursor().message(_("No more insets"));
197 tmpcur.clearSelection();
198 bv->setCursor(tmpcur);
203 /// Moves cursor to the next inset with given code.
204 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
206 gotoInset(bv, vector<InsetCode>(1, code), same_content);
210 /// A map from a Text to the associated text metrics
211 typedef map<Text const *, TextMetrics> TextMetricsCache;
213 enum ScreenUpdateStrategy {
223 /////////////////////////////////////////////////////////////////////
227 /////////////////////////////////////////////////////////////////////
229 struct BufferView::Private
231 Private(BufferView & bv) : update_strategy_(NoScreenUpdate),
233 anchor_pit_(0), anchor_ypos_(0),
234 inlineCompletionUniqueChars_(0),
235 last_inset_(0), clickable_inset_(false),
236 mouse_position_cache_(),
237 bookmark_edit_position_(-1), gui_(0),
238 horiz_scroll_offset_(0), repaint_caret_row_(false)
240 xsel_cache_.set = false;
244 ScrollbarParameters scrollbarParameters_;
246 ScreenUpdateStrategy update_strategy_;
248 CoordCache coord_cache_;
250 /// Estimated average par height for scrollbar.
252 /// this is used to handle XSelection events in the right manner.
261 pit_type anchor_pit_;
265 vector<int> par_height_;
268 DocIterator inlineCompletionPos_;
270 docstring inlineCompletion_;
272 size_t inlineCompletionUniqueChars_;
274 /// keyboard mapping object.
277 /// last visited inset.
278 /** kept to send setMouseHover(false).
279 * Not owned, so don't delete.
281 Inset const * last_inset_;
282 /// are we hovering something that we can click
283 bool clickable_inset_;
285 /// position of the mouse at the time of the last mouse move
286 /// This is used to update the hovering status of inset in
287 /// cases where the buffer is scrolled, but the mouse didn't move.
288 Point mouse_position_cache_;
290 // cache for id of the paragraph which was edited the last time
291 int bookmark_edit_position_;
293 mutable TextMetricsCache text_metrics_;
296 /** Not owned, so don't delete.
298 frontend::GuiBufferViewDelegate * gui_;
300 /// Cache for Find Next
301 FuncRequest search_request_cache_;
304 map<string, Inset *> edited_insets_;
306 /// When the row where the cursor lies is scrolled, this
307 /// contains the scroll offset
308 int horiz_scroll_offset_;
309 /// a slice pointing to the start of the row where the cursor
310 /// is (at last draw time)
311 CursorSlice current_row_slice_;
312 /// a slice pointing to the start of the row where cursor was
313 /// at previous draw event
314 CursorSlice last_row_slice_;
316 /// a slice pointing to where the cursor has been drawn after the current
318 CursorSlice caret_slice_;
319 /// indicates whether the caret slice needs to be repainted in this draw() run.
320 bool repaint_caret_row_;
324 BufferView::BufferView(Buffer & buf)
325 : width_(0), height_(0), full_screen_(false), buffer_(buf),
326 d(new Private(*this))
328 d->xsel_cache_.set = false;
329 d->intl_.initKeyMapper(lyxrc.use_kbmap);
331 d->cursor_.setBuffer(&buf);
332 d->cursor_.push(buffer_.inset());
333 d->cursor_.resetAnchor();
334 d->cursor_.setCurrentFont();
336 buffer_.updatePreviews();
340 BufferView::~BufferView()
342 // current buffer is going to be switched-off, save cursor pos
343 // Ideally, the whole cursor stack should be saved, but session
344 // currently can only handle bottom (whole document) level pit and pos.
345 // That is to say, if a cursor is in a nested inset, it will be
346 // restore to the left of the top level inset.
347 LastFilePosSection::FilePos fp;
348 fp.pit = d->cursor_.bottom().pit();
349 fp.pos = d->cursor_.bottom().pos();
350 theSession().lastFilePos().save(buffer_.fileName(), fp);
353 d->last_inset_->setMouseHover(this, false);
359 int BufferView::rightMargin() const
361 // The value used to be hardcoded to 10, which is 0.1in at 100dpi
362 int const default_margin = Length(0.1, Length::IN).inPixels(0);
363 // The additional test for the case the outliner is opened.
364 if (!full_screen_ || !lyxrc.full_screen_limit
365 || width_ < lyxrc.full_screen_width + 2 * default_margin)
366 return default_margin;
368 return (width_ - lyxrc.full_screen_width) / 2;
372 int BufferView::leftMargin() const
374 return rightMargin();
378 int BufferView::inPixels(Length const & len) const
380 Font const font = buffer().params().getFont();
381 return len.inPixels(workWidth(), theFontMetrics(font).em());
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 Buffer & BufferView::buffer()
427 Buffer const & BufferView::buffer() const
433 bool BufferView::needsFitCursor() const
435 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
436 frontend::FontMetrics const & fm =
437 theFontMetrics(d->cursor_.getFont().fontInfo());
438 int const asc = fm.maxAscent();
439 int const des = fm.maxDescent();
440 Point const p = getPos(d->cursor_);
441 if (p.y_ - asc >= 0 && p.y_ + des < height_)
448 void BufferView::processUpdateFlags(Update::flags flags)
450 // This is close to a hot-path.
451 LYXERR(Debug::PAINTING, "BufferView::processUpdateFlags()"
452 << "[fitcursor = " << (flags & Update::FitCursor)
453 << ", forceupdate = " << (flags & Update::Force)
454 << ", singlepar = " << (flags & Update::SinglePar)
455 << "] buffer: " << &buffer_);
457 // FIXME Does this really need doing here? It's done in updateBuffer, and
458 // if the Buffer doesn't need updating, then do the macros?
459 buffer_.updateMacros();
461 // Now do the first drawing step if needed. This consists on updating
462 // the CoordCache in updateMetrics().
463 // The second drawing step is done in WorkArea::redraw() if needed.
464 // FIXME: is this still true now that Buffer::changed() is used all over?
466 // Case when no explicit update is requested.
468 // no need to redraw anything.
469 d->update_strategy_ = NoScreenUpdate;
473 if (flags == Update::Decoration) {
474 d->update_strategy_ = DecorationUpdate;
475 buffer_.changed(false);
479 if (flags == Update::FitCursor
480 || flags == (Update::Decoration | Update::FitCursor)) {
481 // tell the frontend to update the screen if needed.
482 if (needsFitCursor()) {
486 if (flags & Update::Decoration) {
487 d->update_strategy_ = DecorationUpdate;
488 buffer_.changed(false);
491 // no screen update is needed in principle, but this
492 // could change if cursor row needs horizontal scrolling.
493 d->update_strategy_ = NoScreenUpdate;
494 buffer_.changed(false);
498 bool const full_metrics = flags & Update::Force || !singleParUpdate();
501 // We have to update the full screen metrics.
504 if (!(flags & Update::FitCursor)) {
505 // Nothing to do anymore. Trigger a redraw and return
506 buffer_.changed(false);
510 // updateMetrics() does not update paragraph position
511 // This is done at draw() time. So we need a redraw!
512 buffer_.changed(false);
514 if (needsFitCursor()) {
515 // The cursor is off screen so ensure it is visible.
520 updateHoveredInset();
524 void BufferView::updateScrollbar()
526 if (height_ == 0 && width_ == 0)
529 // We prefer fixed size line scrolling.
530 d->scrollbarParameters_.single_step = defaultRowHeight();
531 // We prefer full screen page scrolling.
532 d->scrollbarParameters_.page_step = height_;
534 Text & t = buffer_.text();
535 TextMetrics & tm = d->text_metrics_[&t];
537 LYXERR(Debug::GUI, " Updating scrollbar: height: "
538 << t.paragraphs().size()
539 << " curr par: " << d->cursor_.bottom().pit()
540 << " default height " << defaultRowHeight());
542 size_t const parsize = t.paragraphs().size();
543 if (d->par_height_.size() != parsize) {
544 d->par_height_.clear();
545 // FIXME: We assume a default paragraph height of 2 rows. This
546 // should probably be pondered with the screen width.
547 d->par_height_.resize(parsize, defaultRowHeight() * 2);
550 // Look at paragraph heights on-screen
551 pair<pit_type, ParagraphMetrics const *> first = tm.first();
552 pair<pit_type, ParagraphMetrics const *> last = tm.last();
553 for (pit_type pit = first.first; pit <= last.first; ++pit) {
554 d->par_height_[pit] = tm.parMetrics(pit).height();
555 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
556 << d->par_height_[pit]);
559 int top_pos = first.second->position() - first.second->ascent();
560 int bottom_pos = last.second->position() + last.second->descent();
561 bool first_visible = first.first == 0 && top_pos >= 0;
562 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
563 if (first_visible && last_visible) {
564 d->scrollbarParameters_.min = 0;
565 d->scrollbarParameters_.max = 0;
569 d->scrollbarParameters_.min = top_pos;
570 for (size_t i = 0; i != size_t(first.first); ++i)
571 d->scrollbarParameters_.min -= d->par_height_[i];
572 d->scrollbarParameters_.max = bottom_pos;
573 for (size_t i = last.first + 1; i != parsize; ++i)
574 d->scrollbarParameters_.max += d->par_height_[i];
576 // The reference is the top position so we remove one page.
577 if (lyxrc.scroll_below_document)
578 d->scrollbarParameters_.max -= minVisiblePart();
580 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
582 // 0 must be inside the range as it denotes the current position
583 if (d->scrollbarParameters_.max < 0)
584 d->scrollbarParameters_.max = 0;
585 if (d->scrollbarParameters_.min > 0)
586 d->scrollbarParameters_.min = 0;
590 ScrollbarParameters const & BufferView::scrollbarParameters() const
592 return d->scrollbarParameters_;
596 docstring BufferView::toolTip(int x, int y) const
598 // Get inset under mouse, if there is one.
599 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
601 // No inset, no tooltip...
603 return covering_inset->toolTip(*this, x, y);
607 string BufferView::contextMenu(int x, int y) const
609 //If there is a selection, return the containing inset menu
610 if (d->cursor_.selection())
611 return d->cursor_.inset().contextMenu(*this, x, y);
613 // Get inset under mouse, if there is one.
614 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
616 return covering_inset->contextMenu(*this, x, y);
618 return buffer_.inset().contextMenu(*this, x, y);
623 void BufferView::scrollDocView(int const value, bool update)
625 // The scrollbar values are relative to the top of the screen, therefore the
626 // offset is equal to the target value.
628 // No scrolling at all? No need to redraw anything
632 // If the offset is less than 2 screen height, prefer to scroll instead.
633 if (abs(value) <= 2 * height_) {
634 d->anchor_ypos_ -= value;
635 buffer_.changed(true);
636 updateHoveredInset();
640 // cut off at the top
641 if (value <= d->scrollbarParameters_.min) {
642 DocIterator dit = doc_iterator_begin(&buffer_);
643 showCursor(dit, false, update);
644 LYXERR(Debug::SCROLLING, "scroll to top");
648 // cut off at the bottom
649 if (value >= d->scrollbarParameters_.max) {
650 DocIterator dit = doc_iterator_end(&buffer_);
652 showCursor(dit, false, update);
653 LYXERR(Debug::SCROLLING, "scroll to bottom");
657 // find paragraph at target position
658 int par_pos = d->scrollbarParameters_.min;
660 for (; i != int(d->par_height_.size()); ++i) {
661 par_pos += d->par_height_[i];
662 if (par_pos >= value)
666 if (par_pos < value) {
667 // It seems we didn't find the correct pit so stay on the safe side and
669 LYXERR0("scrolling position not found!");
670 scrollDocView(d->scrollbarParameters_.max, update);
674 DocIterator dit = doc_iterator_begin(&buffer_);
676 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
677 showCursor(dit, false, update);
681 // FIXME: this method is not working well.
682 void BufferView::setCursorFromScrollbar()
684 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
686 int const height = 2 * defaultRowHeight();
687 int const first = height;
688 int const last = height_ - height;
690 Cursor const & oldcur = d->cursor_;
692 switch (cursorStatus(oldcur)) {
700 int const y = getPos(oldcur).y_;
701 newy = min(last, max(y, first));
705 // We reset the cursor because cursorStatus() does not
706 // work when the cursor is within mathed.
709 tm.setCursorFromCoordinates(cur, 0, newy);
711 // update the bufferview cursor and notify insets
712 // FIXME: Care about the d->cursor_ flags to redraw if needed
713 Cursor old = d->cursor_;
715 // the DEPM call in mouseSetCursor() might have destroyed the
716 // paragraph the cursor is in.
717 bool badcursor = old.fixIfBroken();
718 badcursor |= notifyCursorLeavesOrEnters(old, d->cursor_);
720 d->cursor_.fixIfBroken();
724 Change const BufferView::getCurrentChange() const
726 if (!d->cursor_.selection())
727 return Change(Change::UNCHANGED);
729 DocIterator dit = d->cursor_.selectionBegin();
730 // The selected content might have been changed (see #7685)
731 dit = dit.getInnerText();
732 return dit.paragraph().lookupChange(dit.pos());
736 // this could be used elsewhere as well?
737 // FIXME: This does not work within mathed!
738 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
740 Point const p = getPos(dit);
743 if (p.y_ > workHeight())
749 void BufferView::bookmarkEditPosition()
751 // Don't eat cpu time for each keystroke
752 if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
755 d->bookmark_edit_position_ = d->cursor_.paragraph().id();
759 void BufferView::saveBookmark(unsigned int idx)
761 // tentatively save bookmark, id and pos will be used to
762 // acturately locate a bookmark in a 'live' lyx session.
763 // pit and pos will be updated with bottom level pit/pos
765 if (!buffer_.isInternal()) {
766 theSession().bookmarks().save(
768 d->cursor_.bottom().pit(),
769 d->cursor_.bottom().pos(),
770 d->cursor_.paragraph().id(),
775 // emit message signal.
776 message(_("Save bookmark"));
781 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
782 int top_id, pos_type top_pos)
784 bool success = false;
787 d->cursor_.clearSelection();
789 // if a valid par_id is given, try it first
790 // This is the case for a 'live' bookmark when unique paragraph ID
791 // is used to track bookmarks.
793 dit = buffer_.getParFromID(top_id);
795 dit.pos() = min(dit.paragraph().size(), top_pos);
796 // Some slices of the iterator may not be
797 // reachable (e.g. closed collapsable inset)
798 // so the dociterator may need to be
799 // shortened. Otherwise, setCursor may crash
800 // lyx when the cursor can not be set to these
802 size_t const n = dit.depth();
803 for (size_t i = 0; i < n; ++i)
804 if (!dit[i].inset().editable()) {
812 // if top_id == 0, or searching through top_id failed
813 // This is the case for a 'restored' bookmark when only bottom
814 // (document level) pit was saved. Because of this, bookmark
815 // restoration is inaccurate. If a bookmark was within an inset,
816 // it will be restored to the left of the outmost inset that contains
818 if (bottom_pit < int(buffer_.paragraphs().size())) {
819 dit = doc_iterator_begin(&buffer_);
821 dit.pit() = bottom_pit;
822 dit.pos() = min(bottom_pos, dit.paragraph().size());
827 // Note: only bottom (document) level pit is set.
829 // set the current font.
830 d->cursor_.setCurrentFont();
831 // Do not forget to reset the anchor (see #9912)
832 d->cursor_.resetAnchor();
833 // To center the screen on this new position we need the
834 // paragraph position which is computed at draw() time.
835 // So we need a redraw!
836 buffer_.changed(false);
837 if (needsFitCursor())
845 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
847 if (d->cursor_.real_current_font.isRightToLeft()) {
848 if (d->intl_.keymap == Intl::PRIMARY)
849 d->intl_.keyMapSec();
851 if (d->intl_.keymap == Intl::SECONDARY)
852 d->intl_.keyMapPrim();
855 d->intl_.getTransManager().translateAndInsert(c, t, cur);
859 int BufferView::workWidth() const
865 void BufferView::recenter()
867 showCursor(d->cursor_, true, true);
871 void BufferView::showCursor()
873 showCursor(d->cursor_, false, true);
877 void BufferView::showCursor(DocIterator const & dit,
878 bool recenter, bool update)
880 if (scrollToCursor(dit, recenter) && update) {
881 buffer_.changed(true);
882 updateHoveredInset();
887 void BufferView::scrollToCursor()
889 if (scrollToCursor(d->cursor_, false)) {
890 buffer_.changed(true);
891 updateHoveredInset();
896 bool BufferView::scrollToCursor(DocIterator const & dit, bool const recenter)
898 // We are not properly started yet, delay until resizing is
903 LYXERR(Debug::SCROLLING, "recentering!");
905 CursorSlice const & bot = dit.bottom();
906 TextMetrics & tm = d->text_metrics_[bot.text()];
908 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
909 int bot_pit = bot.pit();
910 if (bot_pit > max_pit) {
911 // FIXME: Why does this happen?
912 LYXERR0("bottom pit is greater that max pit: "
913 << bot_pit << " > " << max_pit);
917 if (bot_pit == tm.first().first - 1)
918 tm.newParMetricsUp();
919 else if (bot_pit == tm.last().first + 1)
920 tm.newParMetricsDown();
922 if (tm.contains(bot_pit)) {
923 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
924 LBUFERR(!pm.rows().empty());
925 // FIXME: smooth scrolling doesn't work in mathed.
926 CursorSlice const & cs = dit.innerTextSlice();
927 int offset = coordOffset(dit).y_;
928 int ypos = pm.position() + offset;
929 Dimension const & row_dim =
930 pm.getRow(cs.pos(), dit.boundary()).dimension();
933 scrolled = scroll(ypos - height_/2);
935 // We try to visualize the whole row, if the row height is larger than
936 // the screen height, we scroll to a heuristic value of height_ / 4.
937 // FIXME: This heuristic value should be replaced by a recursive search
938 // for a row in the inset that can be visualized completely.
939 else if (row_dim.height() > height_) {
940 if (ypos < defaultRowHeight())
941 scrolled = scroll(ypos - height_ / 4);
942 else if (ypos > height_ - defaultRowHeight())
943 scrolled = scroll(ypos - 3 * height_ / 4);
946 // If the top part of the row falls of the screen, we scroll
947 // up to align the top of the row with the top of the screen.
948 else if (ypos - row_dim.ascent() < 0 && ypos < height_) {
949 int ynew = row_dim.ascent();
950 scrolled = scrollUp(ynew - ypos);
953 // If the bottom of the row falls of the screen, we scroll down.
954 else if (ypos + row_dim.descent() > height_ && ypos > 0) {
955 int ynew = height_ - row_dim.descent();
956 scrolled = scrollDown(ypos - ynew);
959 // else, nothing to do, the cursor is already visible so we just return.
960 return scrolled != 0;
963 // fix inline completion position
964 if (d->inlineCompletionPos_.fixIfBroken())
965 d->inlineCompletionPos_ = DocIterator();
967 tm.redoParagraph(bot_pit);
968 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
969 int offset = coordOffset(dit).y_;
971 d->anchor_pit_ = bot_pit;
972 CursorSlice const & cs = dit.innerTextSlice();
973 Dimension const & row_dim =
974 pm.getRow(cs.pos(), dit.boundary()).dimension();
977 d->anchor_ypos_ = height_/2;
978 else if (d->anchor_pit_ == 0)
979 d->anchor_ypos_ = offset + pm.ascent();
980 else if (d->anchor_pit_ == max_pit)
981 d->anchor_ypos_ = height_ - offset - row_dim.descent();
982 else if (offset > height_)
983 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
985 d->anchor_ypos_ = defaultRowHeight() * 2;
991 void BufferView::makeDocumentClass()
993 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
994 buffer_.params().makeDocumentClass();
995 updateDocumentClass(olddc);
999 void BufferView::updateDocumentClass(DocumentClassConstPtr olddc)
1001 message(_("Converting document to new document class..."));
1003 StableDocIterator backcur(d->cursor_);
1004 ErrorList & el = buffer_.errorList("Class Switch");
1005 cap::switchBetweenClasses(
1006 olddc, buffer_.params().documentClassPtr(),
1007 static_cast<InsetText &>(buffer_.inset()), el);
1009 setCursor(backcur.asDocIterator(&buffer_));
1011 buffer_.errors("Class Switch");
1015 /** Return the change status at cursor position, taking into account the
1016 * status at each level of the document iterator (a table in a deleted
1017 * footnote is deleted).
1018 * When \param outer is true, the top slice is not looked at.
1020 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
1022 size_t const depth = dit.depth() - (outer ? 1 : 0);
1024 for (size_t i = 0 ; i < depth ; ++i) {
1025 CursorSlice const & slice = dit[i];
1026 if (!slice.inset().inMathed()
1027 && slice.pos() < slice.paragraph().size()) {
1028 Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
1029 if (ch != Change::UNCHANGED)
1033 return Change::UNCHANGED;
1037 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1039 FuncCode const act = cmd.action();
1041 // Can we use a readonly buffer?
1042 if (buffer_.isReadonly()
1043 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1044 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1045 if (buffer_.hasReadonlyFlag())
1046 flag.message(from_utf8(N_("Document is read-only")));
1048 flag.message(from_utf8(N_("Document has been modified externally")));
1049 flag.setEnabled(false);
1053 // Are we in a DELETED change-tracking region?
1054 if (lookupChangeType(d->cursor_, true) == Change::DELETED
1055 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1056 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1057 flag.message(from_utf8(N_("This portion of the document is deleted.")));
1058 flag.setEnabled(false);
1062 Cursor & cur = d->cursor_;
1064 if (cur.getStatus(cmd, flag))
1069 // FIXME: This is a bit problematic because we don't check if this is
1070 // a document BufferView or not for these LFUNs. We probably have to
1071 // dispatch both to currentBufferView() and, if that fails,
1072 // to documentBufferView(); same as we do now for current Buffer and
1073 // document Buffer. Ideally those LFUN should go to Buffer as they
1074 // operate on the full Buffer and the cursor is only needed either for
1075 // an Undo record or to restore a cursor position. But we don't know
1076 // how to do that inside Buffer of course.
1077 case LFUN_BUFFER_PARAMS_APPLY:
1078 case LFUN_LAYOUT_MODULES_CLEAR:
1079 case LFUN_LAYOUT_MODULE_ADD:
1080 case LFUN_LAYOUT_RELOAD:
1081 case LFUN_TEXTCLASS_APPLY:
1082 case LFUN_TEXTCLASS_LOAD:
1083 flag.setEnabled(!buffer_.isReadonly());
1087 // We do not use the LyXAction flag for readonly because Undo sets the
1088 // buffer clean/dirty status by itself.
1089 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasUndoStack());
1092 // We do not use the LyXAction flag for readonly because Redo sets the
1093 // buffer clean/dirty status by itself.
1094 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasRedoStack());
1096 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1097 case LFUN_FILE_INSERT_PLAINTEXT: {
1098 docstring const fname = cmd.argument();
1099 if (!FileName::isAbsolute(to_utf8(fname))) {
1100 flag.message(_("Absolute filename expected."));
1103 flag.setEnabled(cur.inTexted());
1106 case LFUN_FILE_INSERT:
1107 case LFUN_BOOKMARK_SAVE:
1108 // FIXME: Actually, these LFUNS should be moved to Text
1109 flag.setEnabled(cur.inTexted());
1112 case LFUN_FONT_STATE:
1113 case LFUN_LABEL_INSERT:
1114 case LFUN_INFO_INSERT:
1115 case LFUN_PARAGRAPH_GOTO:
1116 case LFUN_NOTE_NEXT:
1117 case LFUN_REFERENCE_NEXT:
1118 case LFUN_WORD_FIND:
1119 case LFUN_WORD_FIND_FORWARD:
1120 case LFUN_WORD_FIND_BACKWARD:
1121 case LFUN_WORD_REPLACE:
1124 case LFUN_MARK_TOGGLE:
1125 case LFUN_SCREEN_RECENTER:
1126 case LFUN_SCREEN_SHOW_CURSOR:
1127 case LFUN_BIBTEX_DATABASE_ADD:
1128 case LFUN_BIBTEX_DATABASE_DEL:
1129 case LFUN_STATISTICS:
1130 case LFUN_KEYMAP_OFF:
1131 case LFUN_KEYMAP_PRIMARY:
1132 case LFUN_KEYMAP_SECONDARY:
1133 case LFUN_KEYMAP_TOGGLE:
1134 case LFUN_INSET_SELECT_ALL:
1135 flag.setEnabled(true);
1138 case LFUN_WORD_FINDADV: {
1139 FindAndReplaceOptions opt;
1140 istringstream iss(to_utf8(cmd.argument()));
1142 flag.setEnabled(opt.repl_buf_name.empty()
1143 || !buffer_.isReadonly());
1147 case LFUN_LABEL_GOTO:
1148 flag.setEnabled(!cmd.argument().empty()
1149 || getInsetByCode<InsetRef>(cur, REF_CODE));
1152 case LFUN_CHANGES_MERGE:
1153 case LFUN_CHANGE_NEXT:
1154 case LFUN_CHANGE_PREVIOUS:
1155 case LFUN_ALL_CHANGES_ACCEPT:
1156 case LFUN_ALL_CHANGES_REJECT:
1157 flag.setEnabled(buffer_.areChangesPresent());
1160 case LFUN_SCREEN_UP:
1161 case LFUN_SCREEN_DOWN:
1163 case LFUN_SCREEN_UP_SELECT:
1164 case LFUN_SCREEN_DOWN_SELECT:
1165 case LFUN_INSET_FORALL:
1166 flag.setEnabled(true);
1169 case LFUN_LAYOUT_TABULAR:
1170 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1174 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1177 case LFUN_LAYOUT_PARAGRAPH:
1178 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1181 case LFUN_BRANCH_ADD_INSERT:
1182 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1185 case LFUN_DIALOG_SHOW_NEW_INSET:
1186 // FIXME: this is wrong, but I do not understand the
1188 if (cur.inset().lyxCode() == CAPTION_CODE)
1189 return cur.inset().getStatus(cur, cmd, flag);
1190 // FIXME we should consider passthru paragraphs too.
1191 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1194 case LFUN_CITATION_INSERT: {
1195 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1196 // FIXME: This could turn in a recursive hell.
1197 // Shouldn't we use Buffer::getStatus() instead?
1198 flag.setEnabled(lyx::getStatus(fr).enabled());
1201 case LFUN_INSET_APPLY: {
1202 string const name = cmd.getArg(0);
1203 Inset * inset = editedInset(name);
1205 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1206 if (!inset->getStatus(cur, fr, flag)) {
1207 // Every inset is supposed to handle this
1208 LASSERT(false, break);
1211 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1212 flag = lyx::getStatus(fr);
1225 Inset * BufferView::editedInset(string const & name) const
1227 map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1228 return it == d->edited_insets_.end() ? 0 : it->second;
1232 void BufferView::editInset(string const & name, Inset * inset)
1234 d->edited_insets_[name] = inset;
1238 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1240 LYXERR(Debug::ACTION, "BufferView::dispatch: cmd: " << cmd);
1242 string const argument = to_utf8(cmd.argument());
1243 Cursor & cur = d->cursor_;
1246 // Don't dispatch function that does not apply to internal buffers.
1247 if (buffer_.isInternal()
1248 && lyxaction.funcHasFlag(cmd.action(), LyXAction::NoInternal))
1251 // We'll set this back to false if need be.
1252 bool dispatched = true;
1253 buffer_.undo().beginUndoGroup();
1255 FuncCode const act = cmd.action();
1258 case LFUN_BUFFER_PARAMS_APPLY: {
1259 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
1260 cur.recordUndoBufferParams();
1261 istringstream ss(to_utf8(cmd.argument()));
1264 int const unknown_tokens = buffer_.readHeader(lex);
1265 if (unknown_tokens != 0) {
1266 LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1267 << unknown_tokens << " unknown token"
1268 << (unknown_tokens == 1 ? "" : "s"));
1270 updateDocumentClass(olddc);
1272 // We are most certainly here because of a change in the document
1273 // It is then better to make sure that all dialogs are in sync with
1274 // current document settings.
1275 dr.screenUpdate(Update::Force | Update::FitCursor);
1276 dr.forceBufferUpdate();
1280 case LFUN_LAYOUT_MODULES_CLEAR: {
1281 // FIXME: this modifies the document in cap::switchBetweenClasses
1282 // without calling recordUndo. Fix this before using
1283 // recordUndoBufferParams().
1284 cur.recordUndoFullBuffer();
1285 buffer_.params().clearLayoutModules();
1286 makeDocumentClass();
1287 dr.screenUpdate(Update::Force);
1288 dr.forceBufferUpdate();
1292 case LFUN_LAYOUT_MODULE_ADD: {
1293 BufferParams const & params = buffer_.params();
1294 if (!params.layoutModuleCanBeAdded(argument)) {
1295 LYXERR0("Module `" << argument <<
1296 "' cannot be added due to failed requirements or "
1297 "conflicts with installed modules.");
1300 // FIXME: this modifies the document in cap::switchBetweenClasses
1301 // without calling recordUndo. Fix this before using
1302 // recordUndoBufferParams().
1303 cur.recordUndoFullBuffer();
1304 buffer_.params().addLayoutModule(argument);
1305 makeDocumentClass();
1306 dr.screenUpdate(Update::Force);
1307 dr.forceBufferUpdate();
1311 case LFUN_TEXTCLASS_APPLY: {
1312 // since this shortcircuits, the second call is made only if
1314 bool const success =
1315 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1316 LayoutFileList::get().load(argument, buffer_.filePath());
1318 docstring s = bformat(_("The document class `%1$s' "
1319 "could not be loaded."), from_utf8(argument));
1320 frontend::Alert::error(_("Could not load class"), s);
1324 LayoutFile const * old_layout = buffer_.params().baseClass();
1325 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1327 if (old_layout == new_layout)
1331 // Save the old, possibly modular, layout for use in conversion.
1332 // FIXME: this modifies the document in cap::switchBetweenClasses
1333 // without calling recordUndo. Fix this before using
1334 // recordUndoBufferParams().
1335 cur.recordUndoFullBuffer();
1336 buffer_.params().setBaseClass(argument);
1337 makeDocumentClass();
1338 dr.screenUpdate(Update::Force);
1339 dr.forceBufferUpdate();
1343 case LFUN_TEXTCLASS_LOAD: {
1344 // since this shortcircuits, the second call is made only if
1346 bool const success =
1347 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1348 LayoutFileList::get().load(argument, buffer_.filePath());
1350 docstring s = bformat(_("The document class `%1$s' "
1351 "could not be loaded."), from_utf8(argument));
1352 frontend::Alert::error(_("Could not load class"), s);
1357 case LFUN_LAYOUT_RELOAD: {
1358 LayoutFileIndex bc = buffer_.params().baseClassID();
1359 LayoutFileList::get().reset(bc);
1360 buffer_.params().setBaseClass(bc);
1361 makeDocumentClass();
1362 dr.screenUpdate(Update::Force);
1363 dr.forceBufferUpdate();
1368 dr.setMessage(_("Undo"));
1369 cur.clearSelection();
1370 if (!cur.textUndo())
1371 dr.setMessage(_("No further undo information"));
1373 dr.screenUpdate(Update::Force | Update::FitCursor);
1374 dr.forceBufferUpdate();
1378 dr.setMessage(_("Redo"));
1379 cur.clearSelection();
1380 if (!cur.textRedo())
1381 dr.setMessage(_("No further redo information"));
1383 dr.screenUpdate(Update::Force | Update::FitCursor);
1384 dr.forceBufferUpdate();
1387 case LFUN_FONT_STATE:
1388 dr.setMessage(cur.currentState(false));
1391 case LFUN_BOOKMARK_SAVE:
1392 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1395 case LFUN_LABEL_GOTO: {
1396 docstring label = cmd.argument();
1397 if (label.empty()) {
1399 getInsetByCode<InsetRef>(cur, REF_CODE);
1401 label = inset->getParam("reference");
1402 // persistent=false: use temp_bookmark
1406 if (!label.empty()) {
1408 // at the moment, this is redundant, since gotoLabel will
1409 // eventually call LFUN_PARAGRAPH_GOTO, but it seems best
1411 dr.screenUpdate(Update::Force | Update::FitCursor);
1416 case LFUN_PARAGRAPH_GOTO: {
1417 int const id = convert<int>(cmd.getArg(0));
1418 pos_type const pos = convert<int>(cmd.getArg(1));
1421 string const str_id_end = cmd.getArg(2);
1422 string const str_pos_end = cmd.getArg(3);
1424 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1425 b = theBufferList().next(b)) {
1428 cur.setCursor(b->getParFromID(id));
1430 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1434 LYXERR(Debug::INFO, "Paragraph " << cur.paragraph().id()
1435 << " found in buffer `"
1436 << b->absFileName() << "'.");
1438 if (b == &buffer_) {
1440 if (str_id_end.empty() || str_pos_end.empty()) {
1443 mouseSetCursor(cur);
1446 int const id_end = convert<int>(str_id_end);
1447 pos_type const pos_end = convert<int>(str_pos_end);
1448 success = setCursorFromEntries({id, pos},
1452 dr.screenUpdate(Update::Force | Update::FitCursor);
1454 // Switch to other buffer view and resend cmd
1455 lyx::dispatch(FuncRequest(
1456 LFUN_BUFFER_SWITCH, b->absFileName()));
1464 case LFUN_NOTE_NEXT:
1465 gotoInset(this, NOTE_CODE, false);
1468 case LFUN_REFERENCE_NEXT: {
1469 vector<InsetCode> tmp;
1470 tmp.push_back(LABEL_CODE);
1471 tmp.push_back(REF_CODE);
1472 gotoInset(this, tmp, true);
1476 case LFUN_CHANGE_NEXT:
1477 findNextChange(this);
1478 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1479 dr.screenUpdate(Update::Force | Update::FitCursor);
1482 case LFUN_CHANGE_PREVIOUS:
1483 findPreviousChange(this);
1484 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1485 dr.screenUpdate(Update::Force | Update::FitCursor);
1488 case LFUN_CHANGES_MERGE:
1489 if (findNextChange(this) || findPreviousChange(this)) {
1490 dr.screenUpdate(Update::Force | Update::FitCursor);
1491 dr.forceBufferUpdate();
1492 showDialog("changes");
1496 case LFUN_ALL_CHANGES_ACCEPT:
1497 // select complete document
1499 cur.selHandle(true);
1500 buffer_.text().cursorBottom(cur);
1501 // accept everything in a single step to support atomic undo
1502 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1504 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1505 dr.screenUpdate(Update::Force | Update::FitCursor);
1506 dr.forceBufferUpdate();
1509 case LFUN_ALL_CHANGES_REJECT:
1510 // select complete document
1512 cur.selHandle(true);
1513 buffer_.text().cursorBottom(cur);
1514 // reject everything in a single step to support atomic undo
1515 // Note: reject does not work recursively; the user may have to repeat the operation
1516 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1518 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1519 dr.screenUpdate(Update::Force | Update::FitCursor);
1520 dr.forceBufferUpdate();
1523 case LFUN_WORD_FIND_FORWARD:
1524 case LFUN_WORD_FIND_BACKWARD: {
1526 // Would it maybe be better if this variable were view specific anyway?
1527 static docstring last_search;
1528 docstring searched_string;
1530 if (!cmd.argument().empty()) {
1531 last_search = cmd.argument();
1532 searched_string = cmd.argument();
1534 searched_string = last_search;
1537 if (searched_string.empty())
1540 bool const fw = act == LFUN_WORD_FIND_FORWARD;
1541 docstring const data =
1542 find2string(searched_string, true, false, fw);
1543 bool found = lyxfind(this, FuncRequest(LFUN_WORD_FIND, data));
1545 dr.screenUpdate(Update::Force | Update::FitCursor);
1549 case LFUN_WORD_FIND: {
1550 FuncRequest req = cmd;
1551 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1552 req = d->search_request_cache_;
1553 if (req.argument().empty()) {
1554 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1557 if (lyxfind(this, req))
1558 dr.screenUpdate(Update::Force | Update::FitCursor);
1560 d->search_request_cache_ = req;
1564 case LFUN_WORD_REPLACE: {
1565 bool has_deleted = false;
1566 if (cur.selection()) {
1567 DocIterator beg = cur.selectionBegin();
1568 DocIterator end = cur.selectionEnd();
1569 if (beg.pit() == end.pit()) {
1570 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1571 if (!cur.inMathed() && cur.paragraph().isDeleted(p)) {
1578 if (lyxreplace(this, cmd, has_deleted)) {
1579 dr.forceBufferUpdate();
1580 dr.screenUpdate(Update::Force | Update::FitCursor);
1585 case LFUN_WORD_FINDADV: {
1586 FindAndReplaceOptions opt;
1587 istringstream iss(to_utf8(cmd.argument()));
1589 if (findAdv(this, opt)) {
1590 dr.screenUpdate(Update::Force | Update::FitCursor);
1601 cur.clearSelection();
1602 dr.setMessage(from_utf8(N_("Mark off")));
1606 cur.clearSelection();
1608 dr.setMessage(from_utf8(N_("Mark on")));
1611 case LFUN_MARK_TOGGLE:
1612 cur.selection(false);
1615 dr.setMessage(from_utf8(N_("Mark removed")));
1618 dr.setMessage(from_utf8(N_("Mark set")));
1623 case LFUN_SCREEN_SHOW_CURSOR:
1627 case LFUN_SCREEN_RECENTER:
1631 case LFUN_BIBTEX_DATABASE_ADD: {
1632 Cursor tmpcur = cur;
1633 findInset(tmpcur, BIBTEX_CODE, false);
1634 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1637 if (inset->addDatabase(cmd.argument())) {
1638 buffer_.invalidateBibfileCache();
1639 dr.forceBufferUpdate();
1645 case LFUN_BIBTEX_DATABASE_DEL: {
1646 Cursor tmpcur = cur;
1647 findInset(tmpcur, BIBTEX_CODE, false);
1648 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1651 if (inset->delDatabase(cmd.argument())) {
1652 buffer_.invalidateBibfileCache();
1653 dr.forceBufferUpdate();
1659 case LFUN_STATISTICS: {
1660 DocIterator from, to;
1661 if (cur.selection()) {
1662 from = cur.selectionBegin();
1663 to = cur.selectionEnd();
1665 from = doc_iterator_begin(&buffer_);
1666 to = doc_iterator_end(&buffer_);
1668 buffer_.updateStatistics(from, to);
1669 int const words = buffer_.wordCount();
1670 int const chars = buffer_.charCount(false);
1671 int const chars_blanks = buffer_.charCount(true);
1673 if (cur.selection())
1674 message = _("Statistics for the selection:");
1676 message = _("Statistics for the document:");
1679 message += bformat(_("%1$d words"), words);
1681 message += _("One word");
1683 if (chars_blanks != 1)
1684 message += bformat(_("%1$d characters (including blanks)"),
1687 message += _("One character (including blanks)");
1690 message += bformat(_("%1$d characters (excluding blanks)"),
1693 message += _("One character (excluding blanks)");
1695 Alert::information(_("Statistics"), message);
1699 case LFUN_SCREEN_UP:
1700 case LFUN_SCREEN_DOWN: {
1701 Point p = getPos(cur);
1702 // This code has been commented out to enable to scroll down a
1703 // document, even if there are large insets in it (see bug #5465).
1704 /*if (p.y_ < 0 || p.y_ > height_) {
1705 // The cursor is off-screen so recenter before proceeding.
1709 int const scrolled = scroll(act == LFUN_SCREEN_UP
1710 ? -height_ : height_);
1711 if (act == LFUN_SCREEN_UP && scrolled > -height_)
1713 if (act == LFUN_SCREEN_DOWN && scrolled < height_)
1714 p = Point(width_, height_);
1715 bool const in_texted = cur.inTexted();
1716 cur.setCursor(doc_iterator_begin(cur.buffer()));
1717 cur.selHandle(false);
1718 buffer_.changed(true);
1719 updateHoveredInset();
1721 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1722 true, act == LFUN_SCREEN_UP);
1723 //FIXME: what to do with cur.x_target()?
1724 bool update = in_texted && cur.bv().checkDepm(cur, old);
1727 if (update || cur.mark())
1728 dr.screenUpdate(Update::Force | Update::FitCursor);
1730 dr.forceBufferUpdate();
1735 string const scroll_type = cmd.getArg(0);
1736 int scroll_step = 0;
1737 if (scroll_type == "line")
1738 scroll_step = d->scrollbarParameters_.single_step;
1739 else if (scroll_type == "page")
1740 scroll_step = d->scrollbarParameters_.page_step;
1743 string const scroll_quantity = cmd.getArg(1);
1744 if (scroll_quantity == "up")
1745 scrollUp(scroll_step);
1746 else if (scroll_quantity == "down")
1747 scrollDown(scroll_step);
1749 int const scroll_value = convert<int>(scroll_quantity);
1751 scroll(scroll_step * scroll_value);
1753 buffer_.changed(true);
1754 updateHoveredInset();
1755 dr.forceBufferUpdate();
1759 case LFUN_SCREEN_UP_SELECT: {
1760 // FIXME: why is the algorithm different from LFUN_SCREEN_UP?
1761 cur.selHandle(true);
1762 if (isTopScreen()) {
1763 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1767 int y = getPos(cur).y_;
1768 int const ymin = y - height_ + defaultRowHeight();
1769 while (y > ymin && cur.up())
1773 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1777 case LFUN_SCREEN_DOWN_SELECT: {
1778 // FIXME: why is the algorithm different from LFUN_SCREEN_DOWN?
1779 cur.selHandle(true);
1780 if (isBottomScreen()) {
1781 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1785 int y = getPos(cur).y_;
1786 int const ymax = y + height_ - defaultRowHeight();
1787 while (y < ymax && cur.down())
1791 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1796 case LFUN_INSET_SELECT_ALL: {
1797 // true if all cells are selected
1798 bool const all_selected = cur.depth() > 1
1799 && cur.selBegin().at_begin()
1800 && cur.selEnd().at_end();
1801 // true if some cells are selected
1802 bool const cells_selected = cur.depth() > 1
1803 && cur.selBegin().at_cell_begin()
1804 && cur.selEnd().at_cell_end();
1805 if (all_selected || (cells_selected && !cur.inset().isTable())) {
1806 // All the contents of the inset if selected, or only at
1807 // least one cell but inset is not a table.
1808 // Select the inset from outside.
1811 cur.selection(true);
1813 } else if (cells_selected) {
1814 // At least one complete cell is selected and inset is a table.
1819 cur.selection(true);
1820 cur.idx() = cur.lastidx();
1821 cur.pos() = cur.lastpos();
1823 // select current cell
1827 cur.selection(true);
1828 cur.pit() = cur.lastpit();
1829 cur.pos() = cur.lastpos();
1831 cur.setCurrentFont();
1832 dr.screenUpdate(Update::Force);
1837 // This would be in Buffer class if only Cursor did not
1838 // require a bufferview
1839 case LFUN_INSET_FORALL: {
1840 docstring const name = from_utf8(cmd.getArg(0));
1841 string const commandstr = cmd.getLongArg(1);
1842 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
1844 // an arbitrary number to limit number of iterations
1845 const int max_iter = 100000;
1847 Cursor & cur = d->cursor_;
1848 Cursor const savecur = cur;
1850 if (!cur.nextInset())
1852 cur.beginUndoGroup();
1853 while(cur && iterations < max_iter) {
1854 Inset * const ins = cur.nextInset();
1857 docstring insname = ins->layoutName();
1858 while (!insname.empty()) {
1859 if (insname == name || name == from_utf8("*")) {
1861 lyx::dispatch(fr, dr);
1865 size_t const i = insname.rfind(':');
1866 if (i == string::npos)
1868 insname = insname.substr(0, i);
1870 // if we did not delete the inset, skip it
1871 if (!cur.nextInset() || cur.nextInset() == ins)
1876 /** This is a dummy undo record only to remember the cursor
1877 * that has just been set; this will be used on a redo action
1878 * (see ticket #10097)
1880 * FIXME: a better fix would be to have a way to set the
1881 * cursor value directly, but I am not sure it is worth it.
1885 dr.screenUpdate(Update::Force);
1886 dr.forceBufferUpdate();
1888 if (iterations >= max_iter) {
1890 dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
1892 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
1897 case LFUN_BRANCH_ADD_INSERT: {
1898 docstring branch_name = from_utf8(cmd.getArg(0));
1899 if (branch_name.empty())
1900 if (!Alert::askForText(branch_name, _("Branch name")) ||
1901 branch_name.empty())
1904 DispatchResult drtmp;
1905 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
1906 if (drtmp.error()) {
1907 Alert::warning(_("Branch already exists"), drtmp.message());
1910 BranchList & branch_list = buffer_.params().branchlist();
1911 vector<docstring> const branches =
1912 getVectorFromString(branch_name, branch_list.separator());
1913 for (vector<docstring>::const_iterator it = branches.begin();
1914 it != branches.end(); ++it) {
1916 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch_name));
1921 case LFUN_KEYMAP_OFF:
1922 getIntl().keyMapOn(false);
1925 case LFUN_KEYMAP_PRIMARY:
1926 getIntl().keyMapPrim();
1929 case LFUN_KEYMAP_SECONDARY:
1930 getIntl().keyMapSec();
1933 case LFUN_KEYMAP_TOGGLE:
1934 getIntl().toggleKeyMap();
1937 case LFUN_DIALOG_SHOW_NEW_INSET: {
1938 string const name = cmd.getArg(0);
1939 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1940 if (decodeInsetParam(name, data, buffer_))
1941 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1943 lyxerr << "Inset type '" << name <<
1944 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
1948 case LFUN_CITATION_INSERT: {
1949 if (argument.empty()) {
1950 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1953 // we can have one optional argument, delimited by '|'
1954 // citation-insert <key>|<text_before>
1955 // this should be enhanced to also support text_after
1956 // and citation style
1957 string arg = argument;
1959 if (contains(argument, "|")) {
1960 arg = token(argument, '|', 0);
1961 opt1 = token(argument, '|', 1);
1964 // if our cursor is directly in front of or behind a citation inset,
1965 // we will instead add the new key to it.
1966 Inset * inset = cur.nextInset();
1967 if (!inset || inset->lyxCode() != CITE_CODE)
1968 inset = cur.prevInset();
1969 if (inset && inset->lyxCode() == CITE_CODE) {
1970 InsetCitation * icite = static_cast<InsetCitation *>(inset);
1971 if (icite->addKey(arg)) {
1972 dr.forceBufferUpdate();
1973 dr.screenUpdate(Update::FitCursor | Update::SinglePar);
1975 LYXERR0("Discarding optional argument to citation-insert.");
1980 InsetCommandParams icp(CITE_CODE);
1981 icp["key"] = from_utf8(arg);
1983 icp["before"] = from_utf8(opt1);
1984 string icstr = InsetCommand::params2string(icp);
1985 FuncRequest fr(LFUN_INSET_INSERT, icstr);
1990 case LFUN_INSET_APPLY: {
1991 string const name = cmd.getArg(0);
1992 Inset * inset = editedInset(name);
1994 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1998 // put cursor in front of inset.
1999 if (!setCursorFromInset(inset)) {
2000 LASSERT(false, break);
2003 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
2004 inset->dispatch(cur, fr);
2005 dr.screenUpdate(cur.result().screenUpdate());
2006 if (cur.result().needBufferUpdate())
2007 dr.forceBufferUpdate();
2012 // The change of language of buffer belongs to the Buffer class.
2013 // We have to do it here because we need a cursor for Undo.
2014 // When Undo::recordUndoBufferParams() is implemented someday
2015 // LFUN_BUFFER_LANGUAGE should be handled by the Buffer class.
2016 case LFUN_BUFFER_LANGUAGE: {
2017 Language const * oldL = buffer_.params().language;
2018 Language const * newL = languages.getLanguage(argument);
2019 if (!newL || oldL == newL)
2021 if (oldL->rightToLeft() == newL->rightToLeft()) {
2022 cur.recordUndoFullBuffer();
2023 buffer_.changeLanguage(oldL, newL);
2024 cur.setCurrentFont();
2025 dr.forceBufferUpdate();
2030 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2031 case LFUN_FILE_INSERT_PLAINTEXT: {
2032 bool const as_paragraph = (act == LFUN_FILE_INSERT_PLAINTEXT_PARA);
2033 string const fname = to_utf8(cmd.argument());
2034 if (!FileName::isAbsolute(fname))
2035 dr.setMessage(_("Absolute filename expected."));
2037 insertPlaintextFile(FileName(fname), as_paragraph);
2042 // OK, so try the Buffer itself...
2043 buffer_.dispatch(cmd, dr);
2044 dispatched = dr.dispatched();
2048 buffer_.undo().endUndoGroup();
2049 dr.dispatched(dispatched);
2051 // NOTE: The code below is copied from Cursor::dispatch. If you
2052 // need to modify this, please update the other one too.
2054 // notify insets we just entered/left
2055 if (cursor() != old) {
2056 old.beginUndoGroup();
2058 bool badcursor = notifyCursorLeavesOrEnters(old, cursor());
2060 cursor().fixIfBroken();
2061 resetInlineCompletionPos();
2068 docstring const BufferView::requestSelection()
2070 Cursor & cur = d->cursor_;
2072 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
2073 if (!cur.selection()) {
2074 d->xsel_cache_.set = false;
2078 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
2079 if (!d->xsel_cache_.set ||
2080 cur.top() != d->xsel_cache_.cursor ||
2081 cur.realAnchor().top() != d->xsel_cache_.anchor)
2083 d->xsel_cache_.cursor = cur.top();
2084 d->xsel_cache_.anchor = cur.realAnchor().top();
2085 d->xsel_cache_.set = cur.selection();
2086 return cur.selectionAsString(false);
2092 void BufferView::clearSelection()
2094 d->cursor_.clearSelection();
2095 // Clear the selection buffer. Otherwise a subsequent
2096 // middle-mouse-button paste would use the selection buffer,
2097 // not the more current external selection.
2098 cap::clearSelection();
2099 d->xsel_cache_.set = false;
2100 // The buffer did not really change, but this causes the
2101 // redraw we need because we cleared the selection above.
2102 buffer_.changed(false);
2106 void BufferView::resize(int width, int height)
2108 // Update from work area
2112 // Clear the paragraph height cache.
2113 d->par_height_.clear();
2114 // Redo the metrics.
2119 Inset const * BufferView::getCoveringInset(Text const & text,
2122 TextMetrics & tm = d->text_metrics_[&text];
2123 Inset * inset = tm.checkInsetHit(x, y);
2127 if (!inset->descendable(*this))
2128 // No need to go further down if the inset is not
2132 size_t cell_number = inset->nargs();
2133 // Check all the inner cell.
2134 for (size_t i = 0; i != cell_number; ++i) {
2135 Text const * inner_text = inset->getText(i);
2138 Inset const * inset_deeper =
2139 getCoveringInset(*inner_text, x, y);
2141 return inset_deeper;
2149 void BufferView::updateHoveredInset() const
2151 // Get inset under mouse, if there is one.
2152 int const x = d->mouse_position_cache_.x_;
2153 int const y = d->mouse_position_cache_.y_;
2154 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
2156 d->clickable_inset_ = covering_inset && covering_inset->clickable(*this, x, y);
2158 if (covering_inset == d->last_inset_)
2159 // Same inset, no need to do anything...
2162 bool need_redraw = false;
2163 if (d->last_inset_) {
2164 // Remove the hint on the last hovered inset (if any).
2165 need_redraw |= d->last_inset_->setMouseHover(this, false);
2169 if (covering_inset && covering_inset->setMouseHover(this, true)) {
2171 // Only the insets that accept the hover state, do
2172 // clear the last_inset_, so only set the last_inset_
2173 // member if the hovered setting is accepted.
2174 d->last_inset_ = covering_inset;
2178 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
2179 << d->mouse_position_cache_.x_ << ", "
2180 << d->mouse_position_cache_.y_ << ")");
2182 d->update_strategy_ = DecorationUpdate;
2184 // This event (moving without mouse click) is not passed further.
2185 // This should be changed if it is further utilized.
2186 buffer_.changed(false);
2191 void BufferView::clearLastInset(Inset * inset) const
2193 if (d->last_inset_ != inset) {
2194 LYXERR0("Wrong last_inset!");
2201 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
2203 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
2205 // This is only called for mouse related events including
2206 // LFUN_FILE_OPEN generated by drag-and-drop.
2207 FuncRequest cmd = cmd0;
2209 Cursor old = cursor();
2211 cur.push(buffer_.inset());
2212 cur.selection(d->cursor_.selection());
2214 // Either the inset under the cursor or the
2215 // surrounding Text will handle this event.
2217 // make sure we stay within the screen...
2218 cmd.set_y(min(max(cmd.y(), -1), height_));
2220 d->mouse_position_cache_.x_ = cmd.x();
2221 d->mouse_position_cache_.y_ = cmd.y();
2223 if (cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
2224 updateHoveredInset();
2228 // Build temporary cursor.
2229 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x(), cmd.y());
2231 // If inset is not editable, cur.pos() might point behind the
2232 // inset (depending on cmd.x(), cmd.y()). This is needed for
2233 // editing to fix bug 9628, but e.g. the context menu needs a
2234 // cursor in front of the inset.
2235 if ((inset->hasSettings() || !inset->contextMenuName().empty()
2236 || inset->lyxCode() == SEPARATOR_CODE) &&
2237 cur.nextInset() != inset && cur.prevInset() == inset)
2239 } else if (cur.inTexted() && cur.pos()
2240 && cur.paragraph().isEnvSeparator(cur.pos() - 1)) {
2241 // Always place cursor in front of a separator inset.
2245 // Put anchor at the same position.
2248 cur.beginUndoGroup();
2250 // Try to dispatch to an non-editable inset near this position
2251 // via the temp cursor. If the inset wishes to change the real
2252 // cursor it has to do so explicitly by using
2253 // cur.bv().cursor() = cur; (or similar)
2255 inset->dispatch(cur, cmd);
2257 // Now dispatch to the temporary cursor. If the real cursor should
2258 // be modified, the inset's dispatch has to do so explicitly.
2259 if (!inset || !cur.result().dispatched())
2262 // Notify left insets
2264 bool badcursor = old.fixIfBroken() | cur.fixIfBroken();
2265 badcursor |= notifyCursorLeavesOrEnters(old, cur);
2267 cursor().fixIfBroken();
2272 // Do we have a selection?
2273 theSelection().haveSelection(cursor().selection());
2275 if (cur.needBufferUpdate()) {
2276 cur.clearBufferUpdate();
2277 buffer().updateBuffer();
2280 // If the command has been dispatched,
2281 if (cur.result().dispatched() || cur.result().screenUpdate())
2282 processUpdateFlags(cur.result().screenUpdate());
2286 int BufferView::minVisiblePart()
2288 return 2 * defaultRowHeight();
2292 int BufferView::scroll(int y)
2295 return scrollDown(y);
2297 return scrollUp(-y);
2302 int BufferView::scrollDown(int offset)
2304 Text * text = &buffer_.text();
2305 TextMetrics & tm = d->text_metrics_[text];
2306 int const ymax = height_ + offset;
2308 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2309 int bottom_pos = last.second->position() + last.second->descent();
2310 if (lyxrc.scroll_below_document)
2311 bottom_pos += height_ - minVisiblePart();
2312 if (last.first + 1 == int(text->paragraphs().size())) {
2313 if (bottom_pos <= height_)
2315 offset = min(offset, bottom_pos - height_);
2318 if (bottom_pos > ymax)
2320 tm.newParMetricsDown();
2322 d->anchor_ypos_ -= offset;
2327 int BufferView::scrollUp(int offset)
2329 Text * text = &buffer_.text();
2330 TextMetrics & tm = d->text_metrics_[text];
2331 int ymin = - offset;
2333 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2334 int top_pos = first.second->position() - first.second->ascent();
2335 if (first.first == 0) {
2338 offset = min(offset, - top_pos);
2343 tm.newParMetricsUp();
2345 d->anchor_ypos_ += offset;
2350 bool BufferView::setCursorFromRow(int row)
2352 TexRow::TextEntry start, end;
2353 tie(start,end) = buffer_.texrow().getEntriesFromRow(row);
2354 LYXERR(Debug::LATEX,
2355 "setCursorFromRow: for row " << row << ", TexRow has found "
2356 "start (id=" << start.id << ",pos=" << start.pos << "), "
2357 "end (id=" << end.id << ",pos=" << end.pos << ")");
2358 return setCursorFromEntries(start, end);
2362 bool BufferView::setCursorFromEntries(TexRow::TextEntry start,
2363 TexRow::TextEntry end)
2365 DocIterator dit_start, dit_end;
2366 tie(dit_start,dit_end) =
2367 TexRow::getDocIteratorsFromEntries(start, end, buffer_);
2370 // Setting selection start
2371 d->cursor_.clearSelection();
2372 setCursor(dit_start);
2373 // Setting selection end
2375 d->cursor_.resetAnchor();
2376 setCursorSelectionTo(dit_end);
2382 bool BufferView::setCursorFromInset(Inset const * inset)
2384 // are we already there?
2385 if (cursor().nextInset() == inset)
2388 // Inset is not at cursor position. Find it in the document.
2391 while (cur && cur.nextInset() != inset)
2402 void BufferView::gotoLabel(docstring const & label)
2404 ListOfBuffers bufs = buffer().allRelatives();
2405 ListOfBuffers::iterator it = bufs.begin();
2406 for (; it != bufs.end(); ++it) {
2407 Buffer const * buf = *it;
2410 shared_ptr<Toc> toc = buf->tocBackend().toc("label");
2411 Toc::const_iterator toc_it = toc->begin();
2412 Toc::const_iterator end = toc->end();
2413 for (; toc_it != end; ++toc_it) {
2414 if (label == toc_it->str()) {
2415 lyx::dispatch(toc_it->action());
2423 TextMetrics const & BufferView::textMetrics(Text const * t) const
2425 return const_cast<BufferView *>(this)->textMetrics(t);
2429 TextMetrics & BufferView::textMetrics(Text const * t)
2432 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
2433 if (tmc_it == d->text_metrics_.end()) {
2434 tmc_it = d->text_metrics_.insert(
2435 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
2437 return tmc_it->second;
2441 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2444 return textMetrics(t).parMetrics(pit);
2448 int BufferView::workHeight() const
2454 void BufferView::setCursor(DocIterator const & dit)
2457 size_t const n = dit.depth();
2458 for (size_t i = 0; i < n; ++i)
2459 dit[i].inset().edit(d->cursor_, true);
2461 d->cursor_.setCursor(dit);
2462 d->cursor_.selection(false);
2463 d->cursor_.setCurrentFont();
2465 // It seems on general grounds as if this is probably needed, but
2466 // it is not yet clear.
2467 // See bug #7394 and r38388.
2468 // d->cursor.resetAnchor();
2472 void BufferView::setCursorSelectionTo(DocIterator const & dit)
2474 size_t const n = dit.depth();
2475 for (size_t i = 0; i < n; ++i)
2476 dit[i].inset().edit(d->cursor_, true);
2478 d->cursor_.selection(true);
2479 d->cursor_.setCursorSelectionTo(dit);
2480 d->cursor_.setCurrentFont();
2484 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2486 // Would be wrong to delete anything if we have a selection.
2487 if (cur.selection())
2490 bool need_anchor_change = false;
2491 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
2492 need_anchor_change);
2494 if (need_anchor_change)
2502 // we would rather not do this here, but it needs to be done before
2503 // the changed() signal is sent.
2504 buffer_.updateBuffer();
2506 buffer_.changed(true);
2511 bool BufferView::mouseSetCursor(Cursor & cur, bool const select)
2513 LASSERT(&cur.bv() == this, return false);
2516 // this event will clear selection so we save selection for
2517 // persistent selection
2518 cap::saveSelection(cursor());
2520 d->cursor_.macroModeClose();
2521 // If a macro has been finalized, the cursor might have been broken
2524 // Has the cursor just left the inset?
2525 bool const leftinset = (&d->cursor_.inset() != &cur.inset());
2527 d->cursor_.fixIfBroken();
2529 // do the dEPM magic if needed
2530 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2531 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2532 // the leftinset bool would not be necessary (badcursor instead).
2533 bool update = leftinset;
2536 d->cursor_.setSelection();
2537 d->cursor_.setCursorSelectionTo(cur);
2539 if (d->cursor_.inTexted())
2540 update |= checkDepm(cur, d->cursor_);
2541 d->cursor_.resetAnchor();
2542 d->cursor_.setCursor(cur);
2543 d->cursor_.clearSelection();
2545 d->cursor_.boundary(cur.boundary());
2546 d->cursor_.finishUndo();
2547 d->cursor_.setCurrentFont();
2549 cur.forceBufferUpdate();
2554 void BufferView::putSelectionAt(DocIterator const & cur,
2555 int length, bool backwards)
2557 d->cursor_.clearSelection();
2563 d->cursor_.pos() += length;
2564 d->cursor_.setSelection(d->cursor_, -length);
2566 d->cursor_.setSelection(d->cursor_, length);
2571 bool BufferView::selectIfEmpty(DocIterator & cur)
2573 if ((cur.inTexted() && !cur.paragraph().empty())
2574 || (cur.inMathed() && !cur.cell().empty()))
2577 pit_type const beg_pit = cur.pit();
2579 // The paragraph associated to this item isn't
2580 // the first one, so it can be selected
2583 // We have to resort to select the space between the
2584 // end of this item and the begin of the next one
2588 // If it is the only item in the document,
2589 // nothing can be selected
2592 pit_type const end_pit = cur.pit();
2593 pos_type const end_pos = cur.pos();
2594 d->cursor_.clearSelection();
2596 d->cursor_.setCursor(cur);
2597 d->cursor_.pit() = beg_pit;
2598 d->cursor_.pos() = 0;
2599 d->cursor_.selection(false);
2600 d->cursor_.resetAnchor();
2601 d->cursor_.pit() = end_pit;
2602 d->cursor_.pos() = end_pos;
2603 d->cursor_.setSelection();
2608 Cursor & BufferView::cursor()
2614 Cursor const & BufferView::cursor() const
2620 pit_type BufferView::anchor_ref() const
2622 return d->anchor_pit_;
2626 bool BufferView::singleParUpdate()
2628 Text & buftext = buffer_.text();
2629 pit_type const bottom_pit = d->cursor_.bottom().pit();
2630 TextMetrics & tm = textMetrics(&buftext);
2631 int old_height = tm.parMetrics(bottom_pit).height();
2633 // make sure inline completion pointer is ok
2634 if (d->inlineCompletionPos_.fixIfBroken())
2635 d->inlineCompletionPos_ = DocIterator();
2637 // In Single Paragraph mode, rebreak only
2638 // the (main text, not inset!) paragraph containing the cursor.
2639 // (if this paragraph contains insets etc., rebreaking will
2640 // recursively descend)
2641 tm.redoParagraph(bottom_pit);
2642 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
2643 if (pm.height() != old_height)
2644 // Paragraph height has changed so we cannot proceed to
2645 // the singlePar optimisation.
2648 tm.updatePosCache(bottom_pit);
2649 d->update_strategy_ = SingleParUpdate;
2651 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2652 << " y2: " << pm.position() + pm.descent()
2653 << " pit: " << bottom_pit
2654 << " singlepar: 1");
2659 void BufferView::updateMetrics()
2661 if (height_ == 0 || width_ == 0)
2664 Text & buftext = buffer_.text();
2665 pit_type const npit = int(buftext.paragraphs().size());
2667 // Clear out the position cache in case of full screen redraw,
2668 d->coord_cache_.clear();
2670 // Clear out paragraph metrics to avoid having invalid metrics
2671 // in the cache from paragraphs not relayouted below
2672 // The complete text metrics will be redone.
2673 d->text_metrics_.clear();
2675 TextMetrics & tm = textMetrics(&buftext);
2677 // make sure inline completion pointer is ok
2678 if (d->inlineCompletionPos_.fixIfBroken())
2679 d->inlineCompletionPos_ = DocIterator();
2681 if (d->anchor_pit_ >= npit)
2682 // The anchor pit must have been deleted...
2683 d->anchor_pit_ = npit - 1;
2685 // Rebreak anchor paragraph.
2686 tm.redoParagraph(d->anchor_pit_);
2687 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2690 if (d->anchor_pit_ == 0) {
2691 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2693 // Complete buffer visible? Then it's easy.
2694 if (scrollRange == 0)
2695 d->anchor_ypos_ = anchor_pm.ascent();
2697 // avoid empty space above the first row
2698 d->anchor_ypos_ = min(d->anchor_ypos_, anchor_pm.ascent());
2701 anchor_pm.setPosition(d->anchor_ypos_);
2702 tm.updatePosCache(d->anchor_pit_);
2704 LYXERR(Debug::PAINTING, "metrics: "
2705 << " anchor pit = " << d->anchor_pit_
2706 << " anchor ypos = " << d->anchor_ypos_);
2708 // Redo paragraphs above anchor if necessary.
2709 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2710 // We are now just above the anchor paragraph.
2711 pit_type pit1 = d->anchor_pit_ - 1;
2712 for (; pit1 >= 0 && y1 >= 0; --pit1) {
2713 tm.redoParagraph(pit1);
2714 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2716 // Save the paragraph position in the cache.
2718 tm.updatePosCache(pit1);
2722 // Redo paragraphs below the anchor if necessary.
2723 int y2 = d->anchor_ypos_ + anchor_pm.descent();
2724 // We are now just below the anchor paragraph.
2725 pit_type pit2 = d->anchor_pit_ + 1;
2726 for (; pit2 < npit && y2 <= height_; ++pit2) {
2727 tm.redoParagraph(pit2);
2728 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2730 // Save the paragraph position in the cache.
2732 tm.updatePosCache(pit2);
2736 LYXERR(Debug::PAINTING, "Metrics: "
2737 << " anchor pit = " << d->anchor_pit_
2738 << " anchor ypos = " << d->anchor_ypos_
2741 << " pit1 = " << pit1
2742 << " pit2 = " << pit2);
2744 d->update_strategy_ = FullScreenUpdate;
2746 // Now update the positions of insets in the cache.
2749 if (lyxerr.debugging(Debug::WORKAREA)) {
2750 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2751 d->coord_cache_.dump();
2756 void BufferView::updatePosCache()
2758 // this is the "nodraw" drawing stage: only set the positions of the
2759 // insets in metrics cache.
2760 frontend::NullPainter np;
2765 void BufferView::insertLyXFile(FileName const & fname)
2767 LASSERT(d->cursor_.inTexted(), return);
2769 // Get absolute path of file and add ".lyx"
2770 // to the filename if necessary
2771 FileName filename = fileSearch(string(), fname.absFileName(), "lyx");
2773 docstring const disp_fn = makeDisplayPath(filename.absFileName());
2774 // emit message signal.
2775 message(bformat(_("Inserting document %1$s..."), disp_fn));
2778 Buffer buf(filename.absFileName(), false);
2779 if (buf.loadLyXFile() == Buffer::ReadSuccess) {
2780 ErrorList & el = buffer_.errorList("Parse");
2781 // Copy the inserted document error list into the current buffer one.
2782 el = buf.errorList("Parse");
2783 buffer_.undo().recordUndo(d->cursor_);
2784 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2785 buf.params().documentClassPtr(), el);
2786 res = _("Document %1$s inserted.");
2788 res = _("Could not insert document %1$s");
2791 buffer_.changed(true);
2792 // emit message signal.
2793 message(bformat(res, disp_fn));
2797 Point BufferView::coordOffset(DocIterator const & dit) const
2803 // Addup contribution of nested insets, from inside to outside,
2804 // keeping the outer paragraph for a special handling below
2805 for (size_t i = dit.depth() - 1; i >= 1; --i) {
2806 CursorSlice const & sl = dit[i];
2810 // get relative position inside sl.inset()
2811 sl.inset().cursorPos(*this, sl, dit.boundary() && (i + 1 == dit.depth()), xx, yy);
2813 // Make relative position inside of the edited inset relative to sl.inset()
2817 // In case of an RTL inset, the edited inset will be positioned to the left
2820 bool boundary_i = dit.boundary() && i + 1 == dit.depth();
2821 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2826 // remember width for the case that sl.inset() is positioned in an RTL inset
2827 lastw = sl.inset().dimension(*this).wid;
2829 //lyxerr << "Cursor::getPos, i: "
2830 // << i << " x: " << xx << " y: " << y << endl;
2833 // Add contribution of initial rows of outermost paragraph
2834 CursorSlice const & sl = dit[0];
2835 TextMetrics const & tm = textMetrics(sl.text());
2836 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2838 LBUFERR(!pm.rows().empty());
2839 y -= pm.rows()[0].ascent();
2841 // FIXME: document this mess
2843 if (sl.pos() > 0 && dit.depth() == 1) {
2845 if (pos && dit.boundary())
2847 // lyxerr << "coordOffset: boundary:" << dit.boundary() << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2848 rend = pm.pos2row(pos);
2850 rend = pm.pos2row(sl.pos());
2852 size_t rend = pm.pos2row(sl.pos());
2854 for (size_t rit = 0; rit != rend; ++rit)
2855 y += pm.rows()[rit].height();
2856 y += pm.rows()[rend].ascent();
2858 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2860 // Make relative position from the nested inset now bufferview absolute.
2861 int xx = bottom_tm.cursorX(dit.bottom(), dit.boundary() && dit.depth() == 1);
2864 // In the RTL case place the nested inset at the left of the cursor in
2865 // the outer paragraph
2866 bool boundary_1 = dit.boundary() && 1 == dit.depth();
2867 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2875 Point BufferView::getPos(DocIterator const & dit) const
2877 if (!paragraphVisible(dit))
2878 return Point(-1, -1);
2880 CursorSlice const & bot = dit.bottom();
2881 TextMetrics const & tm = textMetrics(bot.text());
2883 // offset from outer paragraph
2884 Point p = coordOffset(dit);
2885 p.y_ += tm.parMetrics(bot.pit()).position();
2890 bool BufferView::paragraphVisible(DocIterator const & dit) const
2892 CursorSlice const & bot = dit.bottom();
2893 TextMetrics const & tm = textMetrics(bot.text());
2895 return tm.contains(bot.pit());
2899 void BufferView::caretPosAndHeight(Point & p, int & h) const
2901 Cursor const & cur = cursor();
2902 Font const font = cur.real_current_font;
2903 frontend::FontMetrics const & fm = theFontMetrics(font);
2904 int const asc = fm.maxAscent();
2905 int const des = fm.maxDescent();
2912 bool BufferView::cursorInView(Point const & p, int h) const
2914 Cursor const & cur = cursor();
2915 // does the cursor touch the screen ?
2916 if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
2922 int BufferView::horizScrollOffset() const
2924 return d->horiz_scroll_offset_;
2928 int BufferView::horizScrollOffset(Text const * text,
2929 pit_type pit, pos_type pos) const
2931 // Is this a row that is currently scrolled?
2932 if (!d->current_row_slice_.empty()
2933 && &text->inset() == d->current_row_slice_.inset().asInsetText()
2934 && pit == d->current_row_slice_.pit()
2935 && pos == d->current_row_slice_.pos())
2936 return d->horiz_scroll_offset_;
2941 bool BufferView::hadHorizScrollOffset(Text const * text,
2942 pit_type pit, pos_type pos) const
2944 return !d->last_row_slice_.empty()
2945 && &text->inset() == d->last_row_slice_.inset().asInsetText()
2946 && pit == d->last_row_slice_.pit()
2947 && pos == d->last_row_slice_.pos();
2951 void BufferView::setCurrentRowSlice(CursorSlice const & rowSlice)
2953 // nothing to do if the cursor was already on this row
2954 if (d->current_row_slice_ == rowSlice) {
2955 d->last_row_slice_ = CursorSlice();
2959 // if the (previous) current row was scrolled, we have to
2960 // remember it in order to repaint it next time.
2961 if (d->horiz_scroll_offset_ != 0)
2962 d->last_row_slice_ = d->current_row_slice_;
2964 d->last_row_slice_ = CursorSlice();
2966 // Since we changed row, the scroll offset is not valid anymore
2967 d->horiz_scroll_offset_ = 0;
2968 d->current_row_slice_ = rowSlice;
2974 bool sliceInRow(CursorSlice const & cs, Text const * text, Row const & row)
2976 return !cs.empty() && cs.text() == text && cs.pit() == row.pit()
2977 && row.pos() <= cs.pos() && cs.pos() <= row.endpos();
2983 bool BufferView::needRepaint(Text const * text, Row const & row) const
2985 return d->repaint_caret_row_ && sliceInRow(d->caret_slice_, text, row);
2989 void BufferView::checkCursorScrollOffset()
2991 CursorSlice rowSlice = d->cursor_.bottom();
2992 TextMetrics const & tm = textMetrics(rowSlice.text());
2994 // Stop if metrics have not been computed yet, since it means
2995 // that there is nothing to do.
2996 if (!tm.contains(rowSlice.pit()))
2998 ParagraphMetrics const & pm = tm.parMetrics(rowSlice.pit());
2999 Row const & row = pm.getRow(rowSlice.pos(),
3000 d->cursor_.boundary() && rowSlice == d->cursor_.top());
3001 rowSlice.pos() = row.pos();
3003 // Set the row on which the cursor lives.
3004 setCurrentRowSlice(rowSlice);
3006 // Current x position of the cursor in pixels
3007 int cur_x = getPos(d->cursor_).x_;
3009 // Horizontal scroll offset of the cursor row in pixels
3010 int offset = d->horiz_scroll_offset_;
3011 int const MARGIN = 2 * theFontMetrics(d->cursor_.real_current_font).em()
3013 if (row.right_x() <= workWidth() - row.right_margin) {
3014 // Row is narrower than the work area, no offset needed.
3017 if (cur_x - offset < MARGIN) {
3018 // cursor would be too far right
3019 offset = cur_x - MARGIN;
3020 } else if (cur_x - offset > workWidth() - MARGIN) {
3021 // cursor would be too far left
3022 offset = cur_x - workWidth() + MARGIN;
3024 // Correct the offset to make sure that we do not scroll too much
3027 if (row.right_x() - offset < workWidth() - row.right_margin)
3028 offset = row.right_x() - workWidth() + row.right_margin;
3031 //lyxerr << "cur_x=" << cur_x << ", offset=" << offset << ", row.wid=" << row.width() << ", margin=" << MARGIN << endl;
3033 if (offset != d->horiz_scroll_offset_)
3034 LYXERR(Debug::PAINTING, "Horiz. scroll offset changed from "
3035 << d->horiz_scroll_offset_ << " to " << offset);
3037 if (d->update_strategy_ == NoScreenUpdate
3038 && (offset != d->horiz_scroll_offset_
3039 || !d->last_row_slice_.empty())) {
3040 // FIXME: if one uses SingleParUpdate, then home/end
3041 // will not work on long rows. Why?
3042 d->update_strategy_ = FullScreenUpdate;
3045 d->horiz_scroll_offset_ = offset;
3049 void BufferView::draw(frontend::Painter & pain, bool paint_caret)
3051 if (height_ == 0 || width_ == 0)
3053 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
3055 Text & text = buffer_.text();
3056 TextMetrics const & tm = d->text_metrics_[&text];
3057 int const y = tm.first().second->position();
3058 PainterInfo pi(this, pain);
3060 /** A repaint of the previous caret row is needed if there is
3061 * caret painted on screen and either
3062 * 1/ a new caret has to be painted at a place different from
3064 * 2/ there is no need for a caret anymore.
3066 d->repaint_caret_row_ = !d->caret_slice_.empty() &&
3067 ((paint_caret && d->cursor_.top() != d->caret_slice_)
3070 // Check whether the row where the cursor lives needs to be scrolled.
3071 // Update the drawing strategy if needed.
3072 checkCursorScrollOffset();
3074 switch (d->update_strategy_) {
3076 case NoScreenUpdate:
3077 // no screen painting is actually needed. In nodraw stage
3078 // however, the different coordinates of insets and paragraphs
3079 // needs to be updated.
3080 LYXERR(Debug::PAINTING, "Strategy: NoScreenUpdate");
3081 pi.full_repaint = false;
3082 if (pain.isNull()) {
3083 pi.full_repaint = true;
3085 } else if (d->repaint_caret_row_) {
3086 pi.full_repaint = false;
3091 case SingleParUpdate:
3092 pi.full_repaint = false;
3093 LYXERR(Debug::PAINTING, "Strategy: SingleParUpdate");
3094 // In general, only the current row of the outermost paragraph
3095 // will be redrawn. Particular cases where selection spans
3096 // multiple paragraph are correctly detected in TextMetrics.
3100 case DecorationUpdate:
3101 // FIXME: We should also distinguish DecorationUpdate to avoid text
3102 // drawing if possible. This is not possible to do easily right now
3103 // because of the single backing pixmap.
3105 case FullScreenUpdate:
3107 LYXERR(Debug::PAINTING,
3108 ((d->update_strategy_ == FullScreenUpdate)
3109 ? "Strategy: FullScreenUpdate"
3110 : "Strategy: DecorationUpdate"));
3112 // The whole screen, including insets, will be refreshed.
3113 pi.full_repaint = true;
3115 // Clear background.
3116 pain.fillRectangle(0, 0, width_, height_,
3117 pi.backgroundColor(&buffer_.inset()));
3122 // and possibly grey out below
3123 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3124 int const y2 = lastpm.second->position() + lastpm.second->descent();
3127 Color color = buffer().isInternal()
3128 ? Color_background : Color_bottomarea;
3129 pain.fillRectangle(0, y2, width_, height_ - y2, color);
3133 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
3135 // The scrollbar needs an update.
3138 // Normalize anchor for next time
3139 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
3140 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3141 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
3142 ParagraphMetrics const & pm = tm.parMetrics(pit);
3143 if (pm.position() + pm.descent() > 0) {
3144 d->anchor_pit_ = pit;
3145 d->anchor_ypos_ = pm.position();
3149 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
3150 << " anchor ypos = " << d->anchor_ypos_);
3152 // Remember what has just been done for the next draw() step
3154 d->caret_slice_ = d->cursor_.top();
3156 d->caret_slice_ = CursorSlice();
3160 void BufferView::message(docstring const & msg)
3163 d->gui_->message(msg);
3167 void BufferView::showDialog(string const & name)
3170 d->gui_->showDialog(name, string());
3174 void BufferView::showDialog(string const & name,
3175 string const & data, Inset * inset)
3178 d->gui_->showDialog(name, data, inset);
3182 void BufferView::updateDialog(string const & name, string const & data)
3185 d->gui_->updateDialog(name, data);
3189 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
3195 // FIXME: Move this out of BufferView again
3196 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
3198 if (!fname.isReadableFile()) {
3199 docstring const error = from_ascii(strerror(errno));
3200 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3201 docstring const text =
3202 bformat(_("Could not read the specified document\n"
3203 "%1$s\ndue to the error: %2$s"), file, error);
3204 Alert::error(_("Could not read file"), text);
3208 if (!fname.isReadableFile()) {
3209 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3210 docstring const text =
3211 bformat(_("%1$s\n is not readable."), file);
3212 Alert::error(_("Could not open file"), text);
3216 // FIXME UNICODE: We don't know the encoding of the file
3217 docstring file_content = fname.fileContents("UTF-8");
3218 if (file_content.empty()) {
3219 Alert::error(_("Reading not UTF-8 encoded file"),
3220 _("The file is not UTF-8 encoded.\n"
3221 "It will be read as local 8Bit-encoded.\n"
3222 "If this does not give the correct result\n"
3223 "then please change the encoding of the file\n"
3224 "to UTF-8 with a program other than LyX.\n"));
3225 file_content = fname.fileContents("local8bit");
3228 return normalize_c(file_content);
3232 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
3234 docstring const tmpstr = contentsOfPlaintextFile(f);
3239 Cursor & cur = cursor();
3240 cap::replaceSelection(cur);
3241 buffer_.undo().recordUndo(cur);
3243 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
3245 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
3247 buffer_.changed(true);
3251 docstring const & BufferView::inlineCompletion() const
3253 return d->inlineCompletion_;
3257 size_t const & BufferView::inlineCompletionUniqueChars() const
3259 return d->inlineCompletionUniqueChars_;
3263 DocIterator const & BufferView::inlineCompletionPos() const
3265 return d->inlineCompletionPos_;
3269 void BufferView::resetInlineCompletionPos()
3271 d->inlineCompletionPos_ = DocIterator();
3275 bool samePar(DocIterator const & a, DocIterator const & b)
3277 if (a.empty() && b.empty())
3279 if (a.empty() || b.empty())
3281 if (a.depth() != b.depth())
3283 return &a.innerParagraph() == &b.innerParagraph();
3287 void BufferView::setInlineCompletion(Cursor const & cur, DocIterator const & pos,
3288 docstring const & completion, size_t uniqueChars)
3290 uniqueChars = min(completion.size(), uniqueChars);
3291 bool changed = d->inlineCompletion_ != completion
3292 || d->inlineCompletionUniqueChars_ != uniqueChars;
3293 bool singlePar = true;
3294 d->inlineCompletion_ = completion;
3295 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
3297 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
3300 DocIterator const & old = d->inlineCompletionPos_;
3302 //lyxerr << "inlineCompletionPos changed" << std::endl;
3303 // old or pos are in another paragraph?
3304 if ((!samePar(cur, pos) && !pos.empty())
3305 || (!samePar(cur, old) && !old.empty())) {
3307 //lyxerr << "different paragraph" << std::endl;
3309 d->inlineCompletionPos_ = pos;
3314 if (singlePar && !(cur.result().screenUpdate() & Update::Force))
3315 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
3317 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::Force);
3322 bool BufferView::clickableInset() const
3324 return d->clickable_inset_;