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();
1375 // we only need to do this if we have deleted or restored a
1376 // BiBTeX inset. but there is no other place to do it. one
1377 // obvious idea is to try to do it in a copy constructor for
1378 // InsetBibTeX, but when that is invoked, the buffer_ member
1379 // is not yet set. another idea is to look at the InsetLists
1380 // of the various paragraphs. but we'd have to recurse through
1381 // the contained insets to make that work. it doesn't seem to
1382 // be worth it, as this will not happen that often.
1383 buffer().invalidateBibfileCache();
1384 buffer().removeBiblioTempFiles();
1388 dr.setMessage(_("Redo"));
1389 cur.clearSelection();
1390 if (!cur.textRedo())
1391 dr.setMessage(_("No further redo information"));
1393 dr.screenUpdate(Update::Force | Update::FitCursor);
1394 dr.forceBufferUpdate();
1396 buffer().invalidateBibfileCache();
1397 buffer().removeBiblioTempFiles();
1400 case LFUN_FONT_STATE:
1401 dr.setMessage(cur.currentState(false));
1404 case LFUN_BOOKMARK_SAVE:
1405 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1408 case LFUN_LABEL_GOTO: {
1409 docstring label = cmd.argument();
1410 if (label.empty()) {
1412 getInsetByCode<InsetRef>(cur, REF_CODE);
1414 label = inset->getParam("reference");
1415 // persistent=false: use temp_bookmark
1419 if (!label.empty()) {
1421 // at the moment, this is redundant, since gotoLabel will
1422 // eventually call LFUN_PARAGRAPH_GOTO, but it seems best
1424 dr.screenUpdate(Update::Force | Update::FitCursor);
1429 case LFUN_PARAGRAPH_GOTO: {
1430 int const id = convert<int>(cmd.getArg(0));
1431 pos_type const pos = convert<int>(cmd.getArg(1));
1434 string const str_id_end = cmd.getArg(2);
1435 string const str_pos_end = cmd.getArg(3);
1437 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1438 b = theBufferList().next(b)) {
1441 cur.setCursor(b->getParFromID(id));
1443 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1447 LYXERR(Debug::INFO, "Paragraph " << cur.paragraph().id()
1448 << " found in buffer `"
1449 << b->absFileName() << "'.");
1451 if (b == &buffer_) {
1453 if (str_id_end.empty() || str_pos_end.empty()) {
1456 mouseSetCursor(cur);
1459 int const id_end = convert<int>(str_id_end);
1460 pos_type const pos_end = convert<int>(str_pos_end);
1461 success = setCursorFromEntries({id, pos},
1465 dr.screenUpdate(Update::Force | Update::FitCursor);
1467 // Switch to other buffer view and resend cmd
1468 lyx::dispatch(FuncRequest(
1469 LFUN_BUFFER_SWITCH, b->absFileName()));
1477 case LFUN_NOTE_NEXT:
1478 gotoInset(this, NOTE_CODE, false);
1481 case LFUN_REFERENCE_NEXT: {
1482 vector<InsetCode> tmp;
1483 tmp.push_back(LABEL_CODE);
1484 tmp.push_back(REF_CODE);
1485 gotoInset(this, tmp, true);
1489 case LFUN_CHANGE_NEXT:
1490 findNextChange(this);
1491 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1492 dr.screenUpdate(Update::Force | Update::FitCursor);
1495 case LFUN_CHANGE_PREVIOUS:
1496 findPreviousChange(this);
1497 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1498 dr.screenUpdate(Update::Force | Update::FitCursor);
1501 case LFUN_CHANGES_MERGE:
1502 if (findNextChange(this) || findPreviousChange(this)) {
1503 dr.screenUpdate(Update::Force | Update::FitCursor);
1504 dr.forceBufferUpdate();
1505 showDialog("changes");
1509 case LFUN_ALL_CHANGES_ACCEPT:
1510 // select complete document
1512 cur.selHandle(true);
1513 buffer_.text().cursorBottom(cur);
1514 // accept everything in a single step to support atomic undo
1515 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1517 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1518 dr.screenUpdate(Update::Force | Update::FitCursor);
1519 dr.forceBufferUpdate();
1522 case LFUN_ALL_CHANGES_REJECT:
1523 // select complete document
1525 cur.selHandle(true);
1526 buffer_.text().cursorBottom(cur);
1527 // reject everything in a single step to support atomic undo
1528 // Note: reject does not work recursively; the user may have to repeat the operation
1529 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1531 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1532 dr.screenUpdate(Update::Force | Update::FitCursor);
1533 dr.forceBufferUpdate();
1536 case LFUN_WORD_FIND_FORWARD:
1537 case LFUN_WORD_FIND_BACKWARD: {
1539 // Would it maybe be better if this variable were view specific anyway?
1540 static docstring last_search;
1541 docstring searched_string;
1543 if (!cmd.argument().empty()) {
1544 last_search = cmd.argument();
1545 searched_string = cmd.argument();
1547 searched_string = last_search;
1550 if (searched_string.empty())
1553 bool const fw = act == LFUN_WORD_FIND_FORWARD;
1554 docstring const data =
1555 find2string(searched_string, true, false, fw);
1556 bool found = lyxfind(this, FuncRequest(LFUN_WORD_FIND, data));
1558 dr.screenUpdate(Update::Force | Update::FitCursor);
1562 case LFUN_WORD_FIND: {
1563 FuncRequest req = cmd;
1564 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1565 req = d->search_request_cache_;
1566 if (req.argument().empty()) {
1567 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1570 if (lyxfind(this, req))
1571 dr.screenUpdate(Update::Force | Update::FitCursor);
1573 d->search_request_cache_ = req;
1577 case LFUN_WORD_REPLACE: {
1578 bool has_deleted = false;
1579 if (cur.selection()) {
1580 DocIterator beg = cur.selectionBegin();
1581 DocIterator end = cur.selectionEnd();
1582 if (beg.pit() == end.pit()) {
1583 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1584 if (!cur.inMathed() && cur.paragraph().isDeleted(p)) {
1591 if (lyxreplace(this, cmd, has_deleted)) {
1592 dr.forceBufferUpdate();
1593 dr.screenUpdate(Update::Force | Update::FitCursor);
1598 case LFUN_WORD_FINDADV: {
1599 FindAndReplaceOptions opt;
1600 istringstream iss(to_utf8(cmd.argument()));
1602 if (findAdv(this, opt)) {
1603 dr.screenUpdate(Update::Force | Update::FitCursor);
1614 cur.clearSelection();
1615 dr.setMessage(from_utf8(N_("Mark off")));
1619 cur.clearSelection();
1621 dr.setMessage(from_utf8(N_("Mark on")));
1624 case LFUN_MARK_TOGGLE:
1625 cur.selection(false);
1628 dr.setMessage(from_utf8(N_("Mark removed")));
1631 dr.setMessage(from_utf8(N_("Mark set")));
1636 case LFUN_SCREEN_SHOW_CURSOR:
1640 case LFUN_SCREEN_RECENTER:
1644 case LFUN_BIBTEX_DATABASE_ADD: {
1645 Cursor tmpcur = cur;
1646 findInset(tmpcur, BIBTEX_CODE, false);
1647 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1650 if (inset->addDatabase(cmd.argument())) {
1651 buffer_.invalidateBibfileCache();
1652 dr.forceBufferUpdate();
1658 case LFUN_BIBTEX_DATABASE_DEL: {
1659 Cursor tmpcur = cur;
1660 findInset(tmpcur, BIBTEX_CODE, false);
1661 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1664 if (inset->delDatabase(cmd.argument())) {
1665 buffer_.invalidateBibfileCache();
1666 dr.forceBufferUpdate();
1672 case LFUN_STATISTICS: {
1673 DocIterator from, to;
1674 if (cur.selection()) {
1675 from = cur.selectionBegin();
1676 to = cur.selectionEnd();
1678 from = doc_iterator_begin(&buffer_);
1679 to = doc_iterator_end(&buffer_);
1681 buffer_.updateStatistics(from, to);
1682 int const words = buffer_.wordCount();
1683 int const chars = buffer_.charCount(false);
1684 int const chars_blanks = buffer_.charCount(true);
1686 if (cur.selection())
1687 message = _("Statistics for the selection:");
1689 message = _("Statistics for the document:");
1692 message += bformat(_("%1$d words"), words);
1694 message += _("One word");
1696 if (chars_blanks != 1)
1697 message += bformat(_("%1$d characters (including blanks)"),
1700 message += _("One character (including blanks)");
1703 message += bformat(_("%1$d characters (excluding blanks)"),
1706 message += _("One character (excluding blanks)");
1708 Alert::information(_("Statistics"), message);
1712 case LFUN_SCREEN_UP:
1713 case LFUN_SCREEN_DOWN: {
1714 Point p = getPos(cur);
1715 // This code has been commented out to enable to scroll down a
1716 // document, even if there are large insets in it (see bug #5465).
1717 /*if (p.y_ < 0 || p.y_ > height_) {
1718 // The cursor is off-screen so recenter before proceeding.
1722 int const scrolled = scroll(act == LFUN_SCREEN_UP
1723 ? -height_ : height_);
1724 if (act == LFUN_SCREEN_UP && scrolled > -height_)
1726 if (act == LFUN_SCREEN_DOWN && scrolled < height_)
1727 p = Point(width_, height_);
1728 bool const in_texted = cur.inTexted();
1729 cur.setCursor(doc_iterator_begin(cur.buffer()));
1730 cur.selHandle(false);
1731 buffer_.changed(true);
1732 updateHoveredInset();
1734 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1735 true, act == LFUN_SCREEN_UP);
1736 //FIXME: what to do with cur.x_target()?
1737 bool update = in_texted && cur.bv().checkDepm(cur, old);
1740 if (update || cur.mark())
1741 dr.screenUpdate(Update::Force | Update::FitCursor);
1743 dr.forceBufferUpdate();
1748 string const scroll_type = cmd.getArg(0);
1749 int scroll_step = 0;
1750 if (scroll_type == "line")
1751 scroll_step = d->scrollbarParameters_.single_step;
1752 else if (scroll_type == "page")
1753 scroll_step = d->scrollbarParameters_.page_step;
1756 string const scroll_quantity = cmd.getArg(1);
1757 if (scroll_quantity == "up")
1758 scrollUp(scroll_step);
1759 else if (scroll_quantity == "down")
1760 scrollDown(scroll_step);
1762 int const scroll_value = convert<int>(scroll_quantity);
1764 scroll(scroll_step * scroll_value);
1766 buffer_.changed(true);
1767 updateHoveredInset();
1768 dr.forceBufferUpdate();
1772 case LFUN_SCREEN_UP_SELECT: {
1773 // FIXME: why is the algorithm different from LFUN_SCREEN_UP?
1774 cur.selHandle(true);
1775 if (isTopScreen()) {
1776 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1780 int y = getPos(cur).y_;
1781 int const ymin = y - height_ + defaultRowHeight();
1782 while (y > ymin && cur.up())
1786 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1790 case LFUN_SCREEN_DOWN_SELECT: {
1791 // FIXME: why is the algorithm different from LFUN_SCREEN_DOWN?
1792 cur.selHandle(true);
1793 if (isBottomScreen()) {
1794 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1798 int y = getPos(cur).y_;
1799 int const ymax = y + height_ - defaultRowHeight();
1800 while (y < ymax && cur.down())
1804 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1809 case LFUN_INSET_SELECT_ALL: {
1810 // true if all cells are selected
1811 bool const all_selected = cur.depth() > 1
1812 && cur.selBegin().at_begin()
1813 && cur.selEnd().at_end();
1814 // true if some cells are selected
1815 bool const cells_selected = cur.depth() > 1
1816 && cur.selBegin().at_cell_begin()
1817 && cur.selEnd().at_cell_end();
1818 if (all_selected || (cells_selected && !cur.inset().isTable())) {
1819 // All the contents of the inset if selected, or only at
1820 // least one cell but inset is not a table.
1821 // Select the inset from outside.
1824 cur.selection(true);
1826 } else if (cells_selected) {
1827 // At least one complete cell is selected and inset is a table.
1832 cur.selection(true);
1833 cur.idx() = cur.lastidx();
1834 cur.pos() = cur.lastpos();
1836 // select current cell
1840 cur.selection(true);
1841 cur.pit() = cur.lastpit();
1842 cur.pos() = cur.lastpos();
1844 cur.setCurrentFont();
1845 dr.screenUpdate(Update::Force);
1850 // This would be in Buffer class if only Cursor did not
1851 // require a bufferview
1852 case LFUN_INSET_FORALL: {
1853 docstring const name = from_utf8(cmd.getArg(0));
1854 string const commandstr = cmd.getLongArg(1);
1855 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
1857 // an arbitrary number to limit number of iterations
1858 const int max_iter = 100000;
1860 Cursor & cur = d->cursor_;
1861 Cursor const savecur = cur;
1863 if (!cur.nextInset())
1865 cur.beginUndoGroup();
1866 while(cur && iterations < max_iter) {
1867 Inset * const ins = cur.nextInset();
1870 docstring insname = ins->layoutName();
1871 while (!insname.empty()) {
1872 if (insname == name || name == from_utf8("*")) {
1874 lyx::dispatch(fr, dr);
1878 size_t const i = insname.rfind(':');
1879 if (i == string::npos)
1881 insname = insname.substr(0, i);
1883 // if we did not delete the inset, skip it
1884 if (!cur.nextInset() || cur.nextInset() == ins)
1889 /** This is a dummy undo record only to remember the cursor
1890 * that has just been set; this will be used on a redo action
1891 * (see ticket #10097)
1893 * FIXME: a better fix would be to have a way to set the
1894 * cursor value directly, but I am not sure it is worth it.
1898 dr.screenUpdate(Update::Force);
1899 dr.forceBufferUpdate();
1901 if (iterations >= max_iter) {
1903 dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
1905 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
1910 case LFUN_BRANCH_ADD_INSERT: {
1911 docstring branch_name = from_utf8(cmd.getArg(0));
1912 if (branch_name.empty())
1913 if (!Alert::askForText(branch_name, _("Branch name")) ||
1914 branch_name.empty())
1917 DispatchResult drtmp;
1918 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
1919 if (drtmp.error()) {
1920 Alert::warning(_("Branch already exists"), drtmp.message());
1923 BranchList & branch_list = buffer_.params().branchlist();
1924 vector<docstring> const branches =
1925 getVectorFromString(branch_name, branch_list.separator());
1926 for (vector<docstring>::const_iterator it = branches.begin();
1927 it != branches.end(); ++it) {
1929 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch_name));
1934 case LFUN_KEYMAP_OFF:
1935 getIntl().keyMapOn(false);
1938 case LFUN_KEYMAP_PRIMARY:
1939 getIntl().keyMapPrim();
1942 case LFUN_KEYMAP_SECONDARY:
1943 getIntl().keyMapSec();
1946 case LFUN_KEYMAP_TOGGLE:
1947 getIntl().toggleKeyMap();
1950 case LFUN_DIALOG_SHOW_NEW_INSET: {
1951 string const name = cmd.getArg(0);
1952 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1953 if (decodeInsetParam(name, data, buffer_))
1954 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1956 lyxerr << "Inset type '" << name <<
1957 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
1961 case LFUN_CITATION_INSERT: {
1962 if (argument.empty()) {
1963 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1966 // we can have one optional argument, delimited by '|'
1967 // citation-insert <key>|<text_before>
1968 // this should be enhanced to also support text_after
1969 // and citation style
1970 string arg = argument;
1972 if (contains(argument, "|")) {
1973 arg = token(argument, '|', 0);
1974 opt1 = token(argument, '|', 1);
1977 // if our cursor is directly in front of or behind a citation inset,
1978 // we will instead add the new key to it.
1979 Inset * inset = cur.nextInset();
1980 if (!inset || inset->lyxCode() != CITE_CODE)
1981 inset = cur.prevInset();
1982 if (inset && inset->lyxCode() == CITE_CODE) {
1983 InsetCitation * icite = static_cast<InsetCitation *>(inset);
1984 if (icite->addKey(arg)) {
1985 dr.forceBufferUpdate();
1986 dr.screenUpdate(Update::FitCursor | Update::SinglePar);
1988 LYXERR0("Discarding optional argument to citation-insert.");
1993 InsetCommandParams icp(CITE_CODE);
1994 icp["key"] = from_utf8(arg);
1996 icp["before"] = from_utf8(opt1);
1997 string icstr = InsetCommand::params2string(icp);
1998 FuncRequest fr(LFUN_INSET_INSERT, icstr);
2003 case LFUN_INSET_APPLY: {
2004 string const name = cmd.getArg(0);
2005 Inset * inset = editedInset(name);
2007 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
2011 // put cursor in front of inset.
2012 if (!setCursorFromInset(inset)) {
2013 LASSERT(false, break);
2016 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
2017 inset->dispatch(cur, fr);
2018 dr.screenUpdate(cur.result().screenUpdate());
2019 if (cur.result().needBufferUpdate())
2020 dr.forceBufferUpdate();
2025 // The change of language of buffer belongs to the Buffer class.
2026 // We have to do it here because we need a cursor for Undo.
2027 // When Undo::recordUndoBufferParams() is implemented someday
2028 // LFUN_BUFFER_LANGUAGE should be handled by the Buffer class.
2029 case LFUN_BUFFER_LANGUAGE: {
2030 Language const * oldL = buffer_.params().language;
2031 Language const * newL = languages.getLanguage(argument);
2032 if (!newL || oldL == newL)
2034 if (oldL->rightToLeft() == newL->rightToLeft()) {
2035 cur.recordUndoFullBuffer();
2036 buffer_.changeLanguage(oldL, newL);
2037 cur.setCurrentFont();
2038 dr.forceBufferUpdate();
2043 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2044 case LFUN_FILE_INSERT_PLAINTEXT: {
2045 bool const as_paragraph = (act == LFUN_FILE_INSERT_PLAINTEXT_PARA);
2046 string const fname = to_utf8(cmd.argument());
2047 if (!FileName::isAbsolute(fname))
2048 dr.setMessage(_("Absolute filename expected."));
2050 insertPlaintextFile(FileName(fname), as_paragraph);
2055 // OK, so try the Buffer itself...
2056 buffer_.dispatch(cmd, dr);
2057 dispatched = dr.dispatched();
2061 buffer_.undo().endUndoGroup();
2062 dr.dispatched(dispatched);
2064 // NOTE: The code below is copied from Cursor::dispatch. If you
2065 // need to modify this, please update the other one too.
2067 // notify insets we just entered/left
2068 if (cursor() != old) {
2069 old.beginUndoGroup();
2071 bool badcursor = notifyCursorLeavesOrEnters(old, cursor());
2073 cursor().fixIfBroken();
2074 resetInlineCompletionPos();
2081 docstring const BufferView::requestSelection()
2083 Cursor & cur = d->cursor_;
2085 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
2086 if (!cur.selection()) {
2087 d->xsel_cache_.set = false;
2091 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
2092 if (!d->xsel_cache_.set ||
2093 cur.top() != d->xsel_cache_.cursor ||
2094 cur.realAnchor().top() != d->xsel_cache_.anchor)
2096 d->xsel_cache_.cursor = cur.top();
2097 d->xsel_cache_.anchor = cur.realAnchor().top();
2098 d->xsel_cache_.set = cur.selection();
2099 return cur.selectionAsString(false);
2105 void BufferView::clearSelection()
2107 d->cursor_.clearSelection();
2108 // Clear the selection buffer. Otherwise a subsequent
2109 // middle-mouse-button paste would use the selection buffer,
2110 // not the more current external selection.
2111 cap::clearSelection();
2112 d->xsel_cache_.set = false;
2113 // The buffer did not really change, but this causes the
2114 // redraw we need because we cleared the selection above.
2115 buffer_.changed(false);
2119 void BufferView::resize(int width, int height)
2121 // Update from work area
2125 // Clear the paragraph height cache.
2126 d->par_height_.clear();
2127 // Redo the metrics.
2132 Inset const * BufferView::getCoveringInset(Text const & text,
2135 TextMetrics & tm = d->text_metrics_[&text];
2136 Inset * inset = tm.checkInsetHit(x, y);
2140 if (!inset->descendable(*this))
2141 // No need to go further down if the inset is not
2145 size_t cell_number = inset->nargs();
2146 // Check all the inner cell.
2147 for (size_t i = 0; i != cell_number; ++i) {
2148 Text const * inner_text = inset->getText(i);
2151 Inset const * inset_deeper =
2152 getCoveringInset(*inner_text, x, y);
2154 return inset_deeper;
2162 void BufferView::updateHoveredInset() const
2164 // Get inset under mouse, if there is one.
2165 int const x = d->mouse_position_cache_.x_;
2166 int const y = d->mouse_position_cache_.y_;
2167 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
2169 d->clickable_inset_ = covering_inset && covering_inset->clickable(*this, x, y);
2171 if (covering_inset == d->last_inset_)
2172 // Same inset, no need to do anything...
2175 bool need_redraw = false;
2176 if (d->last_inset_) {
2177 // Remove the hint on the last hovered inset (if any).
2178 need_redraw |= d->last_inset_->setMouseHover(this, false);
2182 if (covering_inset && covering_inset->setMouseHover(this, true)) {
2184 // Only the insets that accept the hover state, do
2185 // clear the last_inset_, so only set the last_inset_
2186 // member if the hovered setting is accepted.
2187 d->last_inset_ = covering_inset;
2191 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
2192 << d->mouse_position_cache_.x_ << ", "
2193 << d->mouse_position_cache_.y_ << ")");
2195 d->update_strategy_ = DecorationUpdate;
2197 // This event (moving without mouse click) is not passed further.
2198 // This should be changed if it is further utilized.
2199 buffer_.changed(false);
2204 void BufferView::clearLastInset(Inset * inset) const
2206 if (d->last_inset_ != inset) {
2207 LYXERR0("Wrong last_inset!");
2214 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
2216 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
2218 // This is only called for mouse related events including
2219 // LFUN_FILE_OPEN generated by drag-and-drop.
2220 FuncRequest cmd = cmd0;
2222 Cursor old = cursor();
2224 cur.push(buffer_.inset());
2225 cur.selection(d->cursor_.selection());
2227 // Either the inset under the cursor or the
2228 // surrounding Text will handle this event.
2230 // make sure we stay within the screen...
2231 cmd.set_y(min(max(cmd.y(), -1), height_));
2233 d->mouse_position_cache_.x_ = cmd.x();
2234 d->mouse_position_cache_.y_ = cmd.y();
2236 if (cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
2237 updateHoveredInset();
2241 // Build temporary cursor.
2242 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x(), cmd.y());
2244 // If inset is not editable, cur.pos() might point behind the
2245 // inset (depending on cmd.x(), cmd.y()). This is needed for
2246 // editing to fix bug 9628, but e.g. the context menu needs a
2247 // cursor in front of the inset.
2248 if ((inset->hasSettings() || !inset->contextMenuName().empty()
2249 || inset->lyxCode() == SEPARATOR_CODE) &&
2250 cur.nextInset() != inset && cur.prevInset() == inset)
2252 } else if (cur.inTexted() && cur.pos()
2253 && cur.paragraph().isEnvSeparator(cur.pos() - 1)) {
2254 // Always place cursor in front of a separator inset.
2258 // Put anchor at the same position.
2261 cur.beginUndoGroup();
2263 // Try to dispatch to an non-editable inset near this position
2264 // via the temp cursor. If the inset wishes to change the real
2265 // cursor it has to do so explicitly by using
2266 // cur.bv().cursor() = cur; (or similar)
2268 inset->dispatch(cur, cmd);
2270 // Now dispatch to the temporary cursor. If the real cursor should
2271 // be modified, the inset's dispatch has to do so explicitly.
2272 if (!inset || !cur.result().dispatched())
2275 // Notify left insets
2277 bool badcursor = old.fixIfBroken() | cur.fixIfBroken();
2278 badcursor |= notifyCursorLeavesOrEnters(old, cur);
2280 cursor().fixIfBroken();
2285 // Do we have a selection?
2286 theSelection().haveSelection(cursor().selection());
2288 if (cur.needBufferUpdate()) {
2289 cur.clearBufferUpdate();
2290 buffer().updateBuffer();
2293 // If the command has been dispatched,
2294 if (cur.result().dispatched() || cur.result().screenUpdate())
2295 processUpdateFlags(cur.result().screenUpdate());
2299 int BufferView::minVisiblePart()
2301 return 2 * defaultRowHeight();
2305 int BufferView::scroll(int y)
2308 return scrollDown(y);
2310 return scrollUp(-y);
2315 int BufferView::scrollDown(int offset)
2317 Text * text = &buffer_.text();
2318 TextMetrics & tm = d->text_metrics_[text];
2319 int const ymax = height_ + offset;
2321 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2322 int bottom_pos = last.second->position() + last.second->descent();
2323 if (lyxrc.scroll_below_document)
2324 bottom_pos += height_ - minVisiblePart();
2325 if (last.first + 1 == int(text->paragraphs().size())) {
2326 if (bottom_pos <= height_)
2328 offset = min(offset, bottom_pos - height_);
2331 if (bottom_pos > ymax)
2333 tm.newParMetricsDown();
2335 d->anchor_ypos_ -= offset;
2340 int BufferView::scrollUp(int offset)
2342 Text * text = &buffer_.text();
2343 TextMetrics & tm = d->text_metrics_[text];
2344 int ymin = - offset;
2346 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2347 int top_pos = first.second->position() - first.second->ascent();
2348 if (first.first == 0) {
2351 offset = min(offset, - top_pos);
2356 tm.newParMetricsUp();
2358 d->anchor_ypos_ += offset;
2363 bool BufferView::setCursorFromRow(int row)
2365 TexRow::TextEntry start, end;
2366 tie(start,end) = buffer_.texrow().getEntriesFromRow(row);
2367 LYXERR(Debug::LATEX,
2368 "setCursorFromRow: for row " << row << ", TexRow has found "
2369 "start (id=" << start.id << ",pos=" << start.pos << "), "
2370 "end (id=" << end.id << ",pos=" << end.pos << ")");
2371 return setCursorFromEntries(start, end);
2375 bool BufferView::setCursorFromEntries(TexRow::TextEntry start,
2376 TexRow::TextEntry end)
2378 DocIterator dit_start, dit_end;
2379 tie(dit_start,dit_end) =
2380 TexRow::getDocIteratorsFromEntries(start, end, buffer_);
2383 // Setting selection start
2384 d->cursor_.clearSelection();
2385 setCursor(dit_start);
2386 // Setting selection end
2388 d->cursor_.resetAnchor();
2389 setCursorSelectionTo(dit_end);
2395 bool BufferView::setCursorFromInset(Inset const * inset)
2397 // are we already there?
2398 if (cursor().nextInset() == inset)
2401 // Inset is not at cursor position. Find it in the document.
2404 while (cur && cur.nextInset() != inset)
2415 void BufferView::gotoLabel(docstring const & label)
2417 ListOfBuffers bufs = buffer().allRelatives();
2418 ListOfBuffers::iterator it = bufs.begin();
2419 for (; it != bufs.end(); ++it) {
2420 Buffer const * buf = *it;
2423 shared_ptr<Toc> toc = buf->tocBackend().toc("label");
2424 Toc::const_iterator toc_it = toc->begin();
2425 Toc::const_iterator end = toc->end();
2426 for (; toc_it != end; ++toc_it) {
2427 if (label == toc_it->str()) {
2428 lyx::dispatch(toc_it->action());
2436 TextMetrics const & BufferView::textMetrics(Text const * t) const
2438 return const_cast<BufferView *>(this)->textMetrics(t);
2442 TextMetrics & BufferView::textMetrics(Text const * t)
2445 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
2446 if (tmc_it == d->text_metrics_.end()) {
2447 tmc_it = d->text_metrics_.insert(
2448 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
2450 return tmc_it->second;
2454 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2457 return textMetrics(t).parMetrics(pit);
2461 int BufferView::workHeight() const
2467 void BufferView::setCursor(DocIterator const & dit)
2470 size_t const n = dit.depth();
2471 for (size_t i = 0; i < n; ++i)
2472 dit[i].inset().edit(d->cursor_, true);
2474 d->cursor_.setCursor(dit);
2475 d->cursor_.selection(false);
2476 d->cursor_.setCurrentFont();
2478 // It seems on general grounds as if this is probably needed, but
2479 // it is not yet clear.
2480 // See bug #7394 and r38388.
2481 // d->cursor.resetAnchor();
2485 void BufferView::setCursorSelectionTo(DocIterator const & dit)
2487 size_t const n = dit.depth();
2488 for (size_t i = 0; i < n; ++i)
2489 dit[i].inset().edit(d->cursor_, true);
2491 d->cursor_.selection(true);
2492 d->cursor_.setCursorSelectionTo(dit);
2493 d->cursor_.setCurrentFont();
2497 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2499 // Would be wrong to delete anything if we have a selection.
2500 if (cur.selection())
2503 bool need_anchor_change = false;
2504 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
2505 need_anchor_change);
2507 if (need_anchor_change)
2515 // we would rather not do this here, but it needs to be done before
2516 // the changed() signal is sent.
2517 buffer_.updateBuffer();
2519 buffer_.changed(true);
2524 bool BufferView::mouseSetCursor(Cursor & cur, bool const select)
2526 LASSERT(&cur.bv() == this, return false);
2529 // this event will clear selection so we save selection for
2530 // persistent selection
2531 cap::saveSelection(cursor());
2533 d->cursor_.macroModeClose();
2534 // If a macro has been finalized, the cursor might have been broken
2537 // Has the cursor just left the inset?
2538 bool const leftinset = (&d->cursor_.inset() != &cur.inset());
2540 d->cursor_.fixIfBroken();
2542 // do the dEPM magic if needed
2543 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2544 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2545 // the leftinset bool would not be necessary (badcursor instead).
2546 bool update = leftinset;
2549 d->cursor_.setSelection();
2550 d->cursor_.setCursorSelectionTo(cur);
2552 if (d->cursor_.inTexted())
2553 update |= checkDepm(cur, d->cursor_);
2554 d->cursor_.resetAnchor();
2555 d->cursor_.setCursor(cur);
2556 d->cursor_.clearSelection();
2558 d->cursor_.boundary(cur.boundary());
2559 d->cursor_.finishUndo();
2560 d->cursor_.setCurrentFont();
2562 cur.forceBufferUpdate();
2567 void BufferView::putSelectionAt(DocIterator const & cur,
2568 int length, bool backwards)
2570 d->cursor_.clearSelection();
2576 d->cursor_.pos() += length;
2577 d->cursor_.setSelection(d->cursor_, -length);
2579 d->cursor_.setSelection(d->cursor_, length);
2584 bool BufferView::selectIfEmpty(DocIterator & cur)
2586 if ((cur.inTexted() && !cur.paragraph().empty())
2587 || (cur.inMathed() && !cur.cell().empty()))
2590 pit_type const beg_pit = cur.pit();
2592 // The paragraph associated to this item isn't
2593 // the first one, so it can be selected
2596 // We have to resort to select the space between the
2597 // end of this item and the begin of the next one
2601 // If it is the only item in the document,
2602 // nothing can be selected
2605 pit_type const end_pit = cur.pit();
2606 pos_type const end_pos = cur.pos();
2607 d->cursor_.clearSelection();
2609 d->cursor_.setCursor(cur);
2610 d->cursor_.pit() = beg_pit;
2611 d->cursor_.pos() = 0;
2612 d->cursor_.selection(false);
2613 d->cursor_.resetAnchor();
2614 d->cursor_.pit() = end_pit;
2615 d->cursor_.pos() = end_pos;
2616 d->cursor_.setSelection();
2621 Cursor & BufferView::cursor()
2627 Cursor const & BufferView::cursor() const
2633 pit_type BufferView::anchor_ref() const
2635 return d->anchor_pit_;
2639 bool BufferView::singleParUpdate()
2641 Text & buftext = buffer_.text();
2642 pit_type const bottom_pit = d->cursor_.bottom().pit();
2643 TextMetrics & tm = textMetrics(&buftext);
2644 int old_height = tm.parMetrics(bottom_pit).height();
2646 // make sure inline completion pointer is ok
2647 if (d->inlineCompletionPos_.fixIfBroken())
2648 d->inlineCompletionPos_ = DocIterator();
2650 // In Single Paragraph mode, rebreak only
2651 // the (main text, not inset!) paragraph containing the cursor.
2652 // (if this paragraph contains insets etc., rebreaking will
2653 // recursively descend)
2654 tm.redoParagraph(bottom_pit);
2655 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
2656 if (pm.height() != old_height)
2657 // Paragraph height has changed so we cannot proceed to
2658 // the singlePar optimisation.
2661 tm.updatePosCache(bottom_pit);
2662 d->update_strategy_ = SingleParUpdate;
2664 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2665 << " y2: " << pm.position() + pm.descent()
2666 << " pit: " << bottom_pit
2667 << " singlepar: 1");
2672 void BufferView::updateMetrics()
2674 if (height_ == 0 || width_ == 0)
2677 Text & buftext = buffer_.text();
2678 pit_type const npit = int(buftext.paragraphs().size());
2680 // Clear out the position cache in case of full screen redraw,
2681 d->coord_cache_.clear();
2683 // Clear out paragraph metrics to avoid having invalid metrics
2684 // in the cache from paragraphs not relayouted below
2685 // The complete text metrics will be redone.
2686 d->text_metrics_.clear();
2688 TextMetrics & tm = textMetrics(&buftext);
2690 // make sure inline completion pointer is ok
2691 if (d->inlineCompletionPos_.fixIfBroken())
2692 d->inlineCompletionPos_ = DocIterator();
2694 if (d->anchor_pit_ >= npit)
2695 // The anchor pit must have been deleted...
2696 d->anchor_pit_ = npit - 1;
2698 // Rebreak anchor paragraph.
2699 tm.redoParagraph(d->anchor_pit_);
2700 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2703 if (d->anchor_pit_ == 0) {
2704 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2706 // Complete buffer visible? Then it's easy.
2707 if (scrollRange == 0)
2708 d->anchor_ypos_ = anchor_pm.ascent();
2710 // avoid empty space above the first row
2711 d->anchor_ypos_ = min(d->anchor_ypos_, anchor_pm.ascent());
2714 anchor_pm.setPosition(d->anchor_ypos_);
2715 tm.updatePosCache(d->anchor_pit_);
2717 LYXERR(Debug::PAINTING, "metrics: "
2718 << " anchor pit = " << d->anchor_pit_
2719 << " anchor ypos = " << d->anchor_ypos_);
2721 // Redo paragraphs above anchor if necessary.
2722 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2723 // We are now just above the anchor paragraph.
2724 pit_type pit1 = d->anchor_pit_ - 1;
2725 for (; pit1 >= 0 && y1 >= 0; --pit1) {
2726 tm.redoParagraph(pit1);
2727 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2729 // Save the paragraph position in the cache.
2731 tm.updatePosCache(pit1);
2735 // Redo paragraphs below the anchor if necessary.
2736 int y2 = d->anchor_ypos_ + anchor_pm.descent();
2737 // We are now just below the anchor paragraph.
2738 pit_type pit2 = d->anchor_pit_ + 1;
2739 for (; pit2 < npit && y2 <= height_; ++pit2) {
2740 tm.redoParagraph(pit2);
2741 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2743 // Save the paragraph position in the cache.
2745 tm.updatePosCache(pit2);
2749 LYXERR(Debug::PAINTING, "Metrics: "
2750 << " anchor pit = " << d->anchor_pit_
2751 << " anchor ypos = " << d->anchor_ypos_
2754 << " pit1 = " << pit1
2755 << " pit2 = " << pit2);
2757 d->update_strategy_ = FullScreenUpdate;
2759 // Now update the positions of insets in the cache.
2762 if (lyxerr.debugging(Debug::WORKAREA)) {
2763 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2764 d->coord_cache_.dump();
2769 void BufferView::updatePosCache()
2771 // this is the "nodraw" drawing stage: only set the positions of the
2772 // insets in metrics cache.
2773 frontend::NullPainter np;
2778 void BufferView::insertLyXFile(FileName const & fname)
2780 LASSERT(d->cursor_.inTexted(), return);
2782 // Get absolute path of file and add ".lyx"
2783 // to the filename if necessary
2784 FileName filename = fileSearch(string(), fname.absFileName(), "lyx");
2786 docstring const disp_fn = makeDisplayPath(filename.absFileName());
2787 // emit message signal.
2788 message(bformat(_("Inserting document %1$s..."), disp_fn));
2791 Buffer buf(filename.absFileName(), false);
2792 if (buf.loadLyXFile() == Buffer::ReadSuccess) {
2793 ErrorList & el = buffer_.errorList("Parse");
2794 // Copy the inserted document error list into the current buffer one.
2795 el = buf.errorList("Parse");
2796 buffer_.undo().recordUndo(d->cursor_);
2797 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2798 buf.params().documentClassPtr(), el);
2799 res = _("Document %1$s inserted.");
2801 res = _("Could not insert document %1$s");
2804 buffer_.changed(true);
2805 // emit message signal.
2806 message(bformat(res, disp_fn));
2810 Point BufferView::coordOffset(DocIterator const & dit) const
2816 // Addup contribution of nested insets, from inside to outside,
2817 // keeping the outer paragraph for a special handling below
2818 for (size_t i = dit.depth() - 1; i >= 1; --i) {
2819 CursorSlice const & sl = dit[i];
2823 // get relative position inside sl.inset()
2824 sl.inset().cursorPos(*this, sl, dit.boundary() && (i + 1 == dit.depth()), xx, yy);
2826 // Make relative position inside of the edited inset relative to sl.inset()
2830 // In case of an RTL inset, the edited inset will be positioned to the left
2833 bool boundary_i = dit.boundary() && i + 1 == dit.depth();
2834 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2839 // remember width for the case that sl.inset() is positioned in an RTL inset
2840 lastw = sl.inset().dimension(*this).wid;
2842 //lyxerr << "Cursor::getPos, i: "
2843 // << i << " x: " << xx << " y: " << y << endl;
2846 // Add contribution of initial rows of outermost paragraph
2847 CursorSlice const & sl = dit[0];
2848 TextMetrics const & tm = textMetrics(sl.text());
2849 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2851 LBUFERR(!pm.rows().empty());
2852 y -= pm.rows()[0].ascent();
2854 // FIXME: document this mess
2856 if (sl.pos() > 0 && dit.depth() == 1) {
2858 if (pos && dit.boundary())
2860 // lyxerr << "coordOffset: boundary:" << dit.boundary() << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2861 rend = pm.pos2row(pos);
2863 rend = pm.pos2row(sl.pos());
2865 size_t rend = pm.pos2row(sl.pos());
2867 for (size_t rit = 0; rit != rend; ++rit)
2868 y += pm.rows()[rit].height();
2869 y += pm.rows()[rend].ascent();
2871 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2873 // Make relative position from the nested inset now bufferview absolute.
2874 int xx = bottom_tm.cursorX(dit.bottom(), dit.boundary() && dit.depth() == 1);
2877 // In the RTL case place the nested inset at the left of the cursor in
2878 // the outer paragraph
2879 bool boundary_1 = dit.boundary() && 1 == dit.depth();
2880 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2888 Point BufferView::getPos(DocIterator const & dit) const
2890 if (!paragraphVisible(dit))
2891 return Point(-1, -1);
2893 CursorSlice const & bot = dit.bottom();
2894 TextMetrics const & tm = textMetrics(bot.text());
2896 // offset from outer paragraph
2897 Point p = coordOffset(dit);
2898 p.y_ += tm.parMetrics(bot.pit()).position();
2903 bool BufferView::paragraphVisible(DocIterator const & dit) const
2905 CursorSlice const & bot = dit.bottom();
2906 TextMetrics const & tm = textMetrics(bot.text());
2908 return tm.contains(bot.pit());
2912 void BufferView::caretPosAndHeight(Point & p, int & h) const
2914 Cursor const & cur = cursor();
2915 Font const font = cur.real_current_font;
2916 frontend::FontMetrics const & fm = theFontMetrics(font);
2917 int const asc = fm.maxAscent();
2918 int const des = fm.maxDescent();
2925 bool BufferView::cursorInView(Point const & p, int h) const
2927 Cursor const & cur = cursor();
2928 // does the cursor touch the screen ?
2929 if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
2935 int BufferView::horizScrollOffset() const
2937 return d->horiz_scroll_offset_;
2941 int BufferView::horizScrollOffset(Text const * text,
2942 pit_type pit, pos_type pos) const
2944 // Is this a row that is currently scrolled?
2945 if (!d->current_row_slice_.empty()
2946 && &text->inset() == d->current_row_slice_.inset().asInsetText()
2947 && pit == d->current_row_slice_.pit()
2948 && pos == d->current_row_slice_.pos())
2949 return d->horiz_scroll_offset_;
2954 bool BufferView::hadHorizScrollOffset(Text const * text,
2955 pit_type pit, pos_type pos) const
2957 return !d->last_row_slice_.empty()
2958 && &text->inset() == d->last_row_slice_.inset().asInsetText()
2959 && pit == d->last_row_slice_.pit()
2960 && pos == d->last_row_slice_.pos();
2964 void BufferView::setCurrentRowSlice(CursorSlice const & rowSlice)
2966 // nothing to do if the cursor was already on this row
2967 if (d->current_row_slice_ == rowSlice) {
2968 d->last_row_slice_ = CursorSlice();
2972 // if the (previous) current row was scrolled, we have to
2973 // remember it in order to repaint it next time.
2974 if (d->horiz_scroll_offset_ != 0)
2975 d->last_row_slice_ = d->current_row_slice_;
2977 d->last_row_slice_ = CursorSlice();
2979 // Since we changed row, the scroll offset is not valid anymore
2980 d->horiz_scroll_offset_ = 0;
2981 d->current_row_slice_ = rowSlice;
2987 bool sliceInRow(CursorSlice const & cs, Text const * text, Row const & row)
2989 return !cs.empty() && cs.text() == text && cs.pit() == row.pit()
2990 && row.pos() <= cs.pos() && cs.pos() <= row.endpos();
2996 bool BufferView::needRepaint(Text const * text, Row const & row) const
2998 return d->repaint_caret_row_ && sliceInRow(d->caret_slice_, text, row);
3002 void BufferView::checkCursorScrollOffset()
3004 CursorSlice rowSlice = d->cursor_.bottom();
3005 TextMetrics const & tm = textMetrics(rowSlice.text());
3007 // Stop if metrics have not been computed yet, since it means
3008 // that there is nothing to do.
3009 if (!tm.contains(rowSlice.pit()))
3011 ParagraphMetrics const & pm = tm.parMetrics(rowSlice.pit());
3012 Row const & row = pm.getRow(rowSlice.pos(),
3013 d->cursor_.boundary() && rowSlice == d->cursor_.top());
3014 rowSlice.pos() = row.pos();
3016 // Set the row on which the cursor lives.
3017 setCurrentRowSlice(rowSlice);
3019 // Current x position of the cursor in pixels
3020 int cur_x = getPos(d->cursor_).x_;
3022 // Horizontal scroll offset of the cursor row in pixels
3023 int offset = d->horiz_scroll_offset_;
3024 int const MARGIN = 2 * theFontMetrics(d->cursor_.real_current_font).em()
3026 if (row.right_x() <= workWidth() - row.right_margin) {
3027 // Row is narrower than the work area, no offset needed.
3030 if (cur_x - offset < MARGIN) {
3031 // cursor would be too far right
3032 offset = cur_x - MARGIN;
3033 } else if (cur_x - offset > workWidth() - MARGIN) {
3034 // cursor would be too far left
3035 offset = cur_x - workWidth() + MARGIN;
3037 // Correct the offset to make sure that we do not scroll too much
3040 if (row.right_x() - offset < workWidth() - row.right_margin)
3041 offset = row.right_x() - workWidth() + row.right_margin;
3044 //lyxerr << "cur_x=" << cur_x << ", offset=" << offset << ", row.wid=" << row.width() << ", margin=" << MARGIN << endl;
3046 if (offset != d->horiz_scroll_offset_)
3047 LYXERR(Debug::PAINTING, "Horiz. scroll offset changed from "
3048 << d->horiz_scroll_offset_ << " to " << offset);
3050 if (d->update_strategy_ == NoScreenUpdate
3051 && (offset != d->horiz_scroll_offset_
3052 || !d->last_row_slice_.empty())) {
3053 // FIXME: if one uses SingleParUpdate, then home/end
3054 // will not work on long rows. Why?
3055 d->update_strategy_ = FullScreenUpdate;
3058 d->horiz_scroll_offset_ = offset;
3062 void BufferView::draw(frontend::Painter & pain, bool paint_caret)
3064 if (height_ == 0 || width_ == 0)
3066 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
3068 Text & text = buffer_.text();
3069 TextMetrics const & tm = d->text_metrics_[&text];
3070 int const y = tm.first().second->position();
3071 PainterInfo pi(this, pain);
3073 /** A repaint of the previous caret row is needed if there is
3074 * caret painted on screen and either
3075 * 1/ a new caret has to be painted at a place different from
3077 * 2/ there is no need for a caret anymore.
3079 d->repaint_caret_row_ = !d->caret_slice_.empty() &&
3080 ((paint_caret && d->cursor_.top() != d->caret_slice_)
3083 // Check whether the row where the cursor lives needs to be scrolled.
3084 // Update the drawing strategy if needed.
3085 checkCursorScrollOffset();
3087 switch (d->update_strategy_) {
3089 case NoScreenUpdate:
3090 // no screen painting is actually needed. In nodraw stage
3091 // however, the different coordinates of insets and paragraphs
3092 // needs to be updated.
3093 LYXERR(Debug::PAINTING, "Strategy: NoScreenUpdate");
3094 pi.full_repaint = false;
3095 if (pain.isNull()) {
3096 pi.full_repaint = true;
3098 } else if (d->repaint_caret_row_) {
3099 pi.full_repaint = false;
3104 case SingleParUpdate:
3105 pi.full_repaint = false;
3106 LYXERR(Debug::PAINTING, "Strategy: SingleParUpdate");
3107 // In general, only the current row of the outermost paragraph
3108 // will be redrawn. Particular cases where selection spans
3109 // multiple paragraph are correctly detected in TextMetrics.
3113 case DecorationUpdate:
3114 // FIXME: We should also distinguish DecorationUpdate to avoid text
3115 // drawing if possible. This is not possible to do easily right now
3116 // because of the single backing pixmap.
3118 case FullScreenUpdate:
3120 LYXERR(Debug::PAINTING,
3121 ((d->update_strategy_ == FullScreenUpdate)
3122 ? "Strategy: FullScreenUpdate"
3123 : "Strategy: DecorationUpdate"));
3125 // The whole screen, including insets, will be refreshed.
3126 pi.full_repaint = true;
3128 // Clear background.
3129 pain.fillRectangle(0, 0, width_, height_,
3130 pi.backgroundColor(&buffer_.inset()));
3135 // and possibly grey out below
3136 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3137 int const y2 = lastpm.second->position() + lastpm.second->descent();
3140 Color color = buffer().isInternal()
3141 ? Color_background : Color_bottomarea;
3142 pain.fillRectangle(0, y2, width_, height_ - y2, color);
3146 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
3148 // The scrollbar needs an update.
3151 // Normalize anchor for next time
3152 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
3153 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3154 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
3155 ParagraphMetrics const & pm = tm.parMetrics(pit);
3156 if (pm.position() + pm.descent() > 0) {
3157 d->anchor_pit_ = pit;
3158 d->anchor_ypos_ = pm.position();
3162 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
3163 << " anchor ypos = " << d->anchor_ypos_);
3165 // Remember what has just been done for the next draw() step
3167 d->caret_slice_ = d->cursor_.top();
3169 d->caret_slice_ = CursorSlice();
3173 void BufferView::message(docstring const & msg)
3176 d->gui_->message(msg);
3180 void BufferView::showDialog(string const & name)
3183 d->gui_->showDialog(name, string());
3187 void BufferView::showDialog(string const & name,
3188 string const & data, Inset * inset)
3191 d->gui_->showDialog(name, data, inset);
3195 void BufferView::updateDialog(string const & name, string const & data)
3198 d->gui_->updateDialog(name, data);
3202 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
3208 // FIXME: Move this out of BufferView again
3209 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
3211 if (!fname.isReadableFile()) {
3212 docstring const error = from_ascii(strerror(errno));
3213 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3214 docstring const text =
3215 bformat(_("Could not read the specified document\n"
3216 "%1$s\ndue to the error: %2$s"), file, error);
3217 Alert::error(_("Could not read file"), text);
3221 if (!fname.isReadableFile()) {
3222 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3223 docstring const text =
3224 bformat(_("%1$s\n is not readable."), file);
3225 Alert::error(_("Could not open file"), text);
3229 // FIXME UNICODE: We don't know the encoding of the file
3230 docstring file_content = fname.fileContents("UTF-8");
3231 if (file_content.empty()) {
3232 Alert::error(_("Reading not UTF-8 encoded file"),
3233 _("The file is not UTF-8 encoded.\n"
3234 "It will be read as local 8Bit-encoded.\n"
3235 "If this does not give the correct result\n"
3236 "then please change the encoding of the file\n"
3237 "to UTF-8 with a program other than LyX.\n"));
3238 file_content = fname.fileContents("local8bit");
3241 return normalize_c(file_content);
3245 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
3247 docstring const tmpstr = contentsOfPlaintextFile(f);
3252 Cursor & cur = cursor();
3253 cap::replaceSelection(cur);
3254 buffer_.undo().recordUndo(cur);
3256 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
3258 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
3260 buffer_.changed(true);
3264 docstring const & BufferView::inlineCompletion() const
3266 return d->inlineCompletion_;
3270 size_t const & BufferView::inlineCompletionUniqueChars() const
3272 return d->inlineCompletionUniqueChars_;
3276 DocIterator const & BufferView::inlineCompletionPos() const
3278 return d->inlineCompletionPos_;
3282 void BufferView::resetInlineCompletionPos()
3284 d->inlineCompletionPos_ = DocIterator();
3288 bool samePar(DocIterator const & a, DocIterator const & b)
3290 if (a.empty() && b.empty())
3292 if (a.empty() || b.empty())
3294 if (a.depth() != b.depth())
3296 return &a.innerParagraph() == &b.innerParagraph();
3300 void BufferView::setInlineCompletion(Cursor const & cur, DocIterator const & pos,
3301 docstring const & completion, size_t uniqueChars)
3303 uniqueChars = min(completion.size(), uniqueChars);
3304 bool changed = d->inlineCompletion_ != completion
3305 || d->inlineCompletionUniqueChars_ != uniqueChars;
3306 bool singlePar = true;
3307 d->inlineCompletion_ = completion;
3308 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
3310 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
3313 DocIterator const & old = d->inlineCompletionPos_;
3315 //lyxerr << "inlineCompletionPos changed" << std::endl;
3316 // old or pos are in another paragraph?
3317 if ((!samePar(cur, pos) && !pos.empty())
3318 || (!samePar(cur, old) && !old.empty())) {
3320 //lyxerr << "different paragraph" << std::endl;
3322 d->inlineCompletionPos_ = pos;
3327 if (singlePar && !(cur.result().screenUpdate() & Update::Force))
3328 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
3330 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::Force);
3335 bool BufferView::clickableInset() const
3337 return d->clickable_inset_;