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"
40 #include "LyXAction.h"
44 #include "MetricsInfo.h"
45 #include "Paragraph.h"
46 #include "ParagraphParameters.h"
47 #include "ParIterator.h"
50 #include "TextClass.h"
51 #include "TextMetrics.h"
53 #include "TocBackend.h"
54 #include "WordLangTuple.h"
56 #include "insets/InsetBibtex.h"
57 #include "insets/InsetCitation.h"
58 #include "insets/InsetCommand.h" // ChangeRefs
59 #include "insets/InsetExternal.h"
60 #include "insets/InsetGraphics.h"
61 #include "insets/InsetNote.h"
62 #include "insets/InsetRef.h"
63 #include "insets/InsetText.h"
65 #include "frontends/alert.h"
66 #include "frontends/Application.h"
67 #include "frontends/Delegates.h"
68 #include "frontends/FontMetrics.h"
69 #include "frontends/Painter.h"
70 #include "frontends/Selection.h"
72 #include "support/convert.h"
73 #include "support/debug.h"
74 #include "support/ExceptionMessage.h"
75 #include "support/filetools.h"
76 #include "support/gettext.h"
77 #include "support/lassert.h"
78 #include "support/lstrings.h"
79 #include "support/Package.h"
80 #include "support/types.h"
90 using namespace lyx::support;
94 namespace Alert = frontend::Alert;
98 /// Return an inset of this class if it exists at the current cursor position
100 T * getInsetByCode(Cursor const & cur, InsetCode code)
102 DocIterator it = cur;
103 Inset * inset = it.nextInset();
104 if (inset && inset->lyxCode() == code)
105 return static_cast<T*>(inset);
110 /// Note that comparing contents can only be used for InsetCommand
111 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
112 docstring const & contents)
114 DocIterator tmpdit = dit;
117 Inset const * inset = tmpdit.nextInset();
119 bool const valid_code = std::find(codes.begin(), codes.end(),
120 inset->lyxCode()) != codes.end();
121 InsetCommand const * ic = inset->asInsetCommand();
122 bool const same_or_no_contents = contents.empty()
123 || (ic && (ic->getFirstNonOptParam() == contents));
125 if (valid_code && same_or_no_contents) {
130 tmpdit.forwardInset();
137 /// Looks for next inset with one of the given codes.
138 /// Note that same_content can only be used for InsetCommand
139 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
143 DocIterator tmpdit = dit;
144 tmpdit.forwardInset();
148 Inset const * inset = tmpdit.nextInset();
149 if (same_content && inset) {
150 InsetCommand const * ic = inset->asInsetCommand();
152 bool const valid_code = std::find(codes.begin(), codes.end(),
153 ic->lyxCode()) != codes.end();
155 contents = ic->getFirstNonOptParam();
159 if (!findNextInset(tmpdit, codes, contents)) {
160 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
161 Inset * inset = &tmpdit.bottom().inset();
162 tmpdit = doc_iterator_begin(&inset->buffer(), inset);
163 if (!findNextInset(tmpdit, codes, contents))
175 /// Looks for next inset with the given code
176 void findInset(DocIterator & dit, InsetCode code, bool same_content)
178 findInset(dit, vector<InsetCode>(1, code), same_content);
182 /// Moves cursor to the next inset with one of the given codes.
183 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
186 Cursor tmpcur = bv->cursor();
187 if (!findInset(tmpcur, codes, same_content)) {
188 bv->cursor().message(_("No more insets"));
192 tmpcur.clearSelection();
193 bv->setCursor(tmpcur);
198 /// Moves cursor to the next inset with given code.
199 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
201 gotoInset(bv, vector<InsetCode>(1, code), same_content);
205 /// A map from a Text to the associated text metrics
206 typedef map<Text const *, TextMetrics> TextMetricsCache;
208 enum ScreenUpdateStrategy {
218 /////////////////////////////////////////////////////////////////////
222 /////////////////////////////////////////////////////////////////////
224 struct BufferView::Private
226 Private(BufferView & bv): wh_(0), cursor_(bv),
227 anchor_pit_(0), anchor_ypos_(0),
228 inlineCompletionUniqueChars_(0),
229 last_inset_(0), clickable_inset_(false),
230 mouse_position_cache_(),
231 bookmark_edit_position_(-1), gui_(0)
235 ScrollbarParameters scrollbarParameters_;
237 ScreenUpdateStrategy update_strategy_;
239 CoordCache coord_cache_;
241 /// Estimated average par height for scrollbar.
243 /// this is used to handle XSelection events in the right manner.
252 pit_type anchor_pit_;
256 vector<int> par_height_;
259 DocIterator inlineCompletionPos_;
261 docstring inlineCompletion_;
263 size_t inlineCompletionUniqueChars_;
265 /// keyboard mapping object.
268 /// last visited inset.
269 /** kept to send setMouseHover(false).
270 * Not owned, so don't delete.
272 Inset const * last_inset_;
273 /// are we hovering something that we can click
274 bool clickable_inset_;
276 /// position of the mouse at the time of the last mouse move
277 /// This is used to update the hovering status of inset in
278 /// cases where the buffer is scrolled, but the mouse didn't move.
279 Point mouse_position_cache_;
281 // cache for id of the paragraph which was edited the last time
282 int bookmark_edit_position_;
284 mutable TextMetricsCache text_metrics_;
287 /** Not owned, so don't delete.
289 frontend::GuiBufferViewDelegate * gui_;
291 /// Cache for Find Next
292 FuncRequest search_request_cache_;
295 map<string, Inset *> edited_insets_;
299 BufferView::BufferView(Buffer & buf)
300 : width_(0), height_(0), full_screen_(false), buffer_(buf),
301 d(new Private(*this))
303 d->xsel_cache_.set = false;
304 d->intl_.initKeyMapper(lyxrc.use_kbmap);
306 d->cursor_.setBuffer(&buf);
307 d->cursor_.push(buffer_.inset());
308 d->cursor_.resetAnchor();
309 d->cursor_.setCurrentFont();
311 buffer_.updatePreviews();
315 BufferView::~BufferView()
317 // current buffer is going to be switched-off, save cursor pos
318 // Ideally, the whole cursor stack should be saved, but session
319 // currently can only handle bottom (whole document) level pit and pos.
320 // That is to say, if a cursor is in a nested inset, it will be
321 // restore to the left of the top level inset.
322 LastFilePosSection::FilePos fp;
323 fp.pit = d->cursor_.bottom().pit();
324 fp.pos = d->cursor_.bottom().pos();
325 theSession().lastFilePos().save(buffer_.fileName(), fp);
328 d->last_inset_->setMouseHover(this, false);
334 int BufferView::rightMargin() const
336 // The additional test for the case the outliner is opened.
338 !lyxrc.full_screen_limit ||
339 width_ < lyxrc.full_screen_width + 20)
342 return (width_ - lyxrc.full_screen_width) / 2;
346 int BufferView::leftMargin() const
348 return rightMargin();
352 bool BufferView::isTopScreen() const
354 return d->scrollbarParameters_.position == d->scrollbarParameters_.min;
358 bool BufferView::isBottomScreen() const
360 return d->scrollbarParameters_.position == d->scrollbarParameters_.max;
364 Intl & BufferView::getIntl()
370 Intl const & BufferView::getIntl() const
376 CoordCache & BufferView::coordCache()
378 return d->coord_cache_;
382 CoordCache const & BufferView::coordCache() const
384 return d->coord_cache_;
388 Buffer & BufferView::buffer()
394 Buffer const & BufferView::buffer() const
400 bool BufferView::fitCursor()
402 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
403 frontend::FontMetrics const & fm =
404 theFontMetrics(d->cursor_.getFont().fontInfo());
405 int const asc = fm.maxAscent();
406 int const des = fm.maxDescent();
407 Point const p = getPos(d->cursor_);
408 if (p.y_ - asc >= 0 && p.y_ + des < height_)
415 void BufferView::processUpdateFlags(Update::flags flags)
417 // This is close to a hot-path.
418 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
419 << "[fitcursor = " << (flags & Update::FitCursor)
420 << ", forceupdate = " << (flags & Update::Force)
421 << ", singlepar = " << (flags & Update::SinglePar)
422 << "] buffer: " << &buffer_);
424 // FIXME Does this really need doing here? It's done in updateBuffer, and
425 // if the Buffer doesn't need updating, then do the macros?
426 buffer_.updateMacros();
428 // Now do the first drawing step if needed. This consists on updating
429 // the CoordCache in updateMetrics().
430 // The second drawing step is done in WorkArea::redraw() if needed.
432 // Case when no explicit update is requested.
434 // no need to redraw anything.
435 d->update_strategy_ = NoScreenUpdate;
439 if (flags == Update::Decoration) {
440 d->update_strategy_ = DecorationUpdate;
441 buffer_.changed(false);
445 if (flags == Update::FitCursor
446 || flags == (Update::Decoration | Update::FitCursor)) {
447 // tell the frontend to update the screen if needed.
452 if (flags & Update::Decoration) {
453 d->update_strategy_ = DecorationUpdate;
454 buffer_.changed(false);
457 // no screen update is needed.
458 d->update_strategy_ = NoScreenUpdate;
462 bool const full_metrics = flags & Update::Force || !singleParUpdate();
465 // We have to update the full screen metrics.
468 if (!(flags & Update::FitCursor)) {
469 // Nothing to do anymore. Trigger a redraw and return
470 buffer_.changed(false);
474 // updateMetrics() does not update paragraph position
475 // This is done at draw() time. So we need a redraw!
476 buffer_.changed(false);
479 // The cursor is off screen so ensure it is visible.
484 updateHoveredInset();
488 void BufferView::updateScrollbar()
490 if (height_ == 0 && width_ == 0)
493 // We prefer fixed size line scrolling.
494 d->scrollbarParameters_.single_step = defaultRowHeight();
495 // We prefer full screen page scrolling.
496 d->scrollbarParameters_.page_step = height_;
498 Text & t = buffer_.text();
499 TextMetrics & tm = d->text_metrics_[&t];
501 LYXERR(Debug::GUI, " Updating scrollbar: height: "
502 << t.paragraphs().size()
503 << " curr par: " << d->cursor_.bottom().pit()
504 << " default height " << defaultRowHeight());
506 size_t const parsize = t.paragraphs().size();
507 if (d->par_height_.size() != parsize) {
508 d->par_height_.clear();
509 // FIXME: We assume a default paragraph height of 2 rows. This
510 // should probably be pondered with the screen width.
511 d->par_height_.resize(parsize, defaultRowHeight() * 2);
514 // Look at paragraph heights on-screen
515 pair<pit_type, ParagraphMetrics const *> first = tm.first();
516 pair<pit_type, ParagraphMetrics const *> last = tm.last();
517 for (pit_type pit = first.first; pit <= last.first; ++pit) {
518 d->par_height_[pit] = tm.parMetrics(pit).height();
519 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
520 << d->par_height_[pit]);
523 int top_pos = first.second->position() - first.second->ascent();
524 int bottom_pos = last.second->position() + last.second->descent();
525 bool first_visible = first.first == 0 && top_pos >= 0;
526 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
527 if (first_visible && last_visible) {
528 d->scrollbarParameters_.min = 0;
529 d->scrollbarParameters_.max = 0;
533 d->scrollbarParameters_.min = top_pos;
534 for (size_t i = 0; i != size_t(first.first); ++i)
535 d->scrollbarParameters_.min -= d->par_height_[i];
536 d->scrollbarParameters_.max = bottom_pos;
537 for (size_t i = last.first + 1; i != parsize; ++i)
538 d->scrollbarParameters_.max += d->par_height_[i];
540 d->scrollbarParameters_.position = 0;
541 // The reference is the top position so we remove one page.
542 if (lyxrc.scroll_below_document)
543 d->scrollbarParameters_.max -= minVisiblePart();
545 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
549 ScrollbarParameters const & BufferView::scrollbarParameters() const
551 return d->scrollbarParameters_;
555 docstring BufferView::toolTip(int x, int y) const
557 // Get inset under mouse, if there is one.
558 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
560 // No inset, no tooltip...
562 return covering_inset->toolTip(*this, x, y);
566 string BufferView::contextMenu(int x, int y) const
568 //If there is a selection, return the containing inset menu
569 if (d->cursor_.selection())
570 return d->cursor_.inset().contextMenu(*this, x, y);
572 // Get inset under mouse, if there is one.
573 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
575 return covering_inset->contextMenu(*this, x, y);
577 return buffer_.inset().contextMenu(*this, x, y);
581 void BufferView::scrollDocView(int value, bool update)
583 int const offset = value - d->scrollbarParameters_.position;
585 // No scrolling at all? No need to redraw anything
589 // If the offset is less than 2 screen height, prefer to scroll instead.
590 if (abs(offset) <= 2 * height_) {
591 d->anchor_ypos_ -= offset;
592 buffer_.changed(true);
593 updateHoveredInset();
597 // cut off at the top
598 if (value <= d->scrollbarParameters_.min) {
599 DocIterator dit = doc_iterator_begin(&buffer_);
600 showCursor(dit, false, update);
601 LYXERR(Debug::SCROLLING, "scroll to top");
605 // cut off at the bottom
606 if (value >= d->scrollbarParameters_.max) {
607 DocIterator dit = doc_iterator_end(&buffer_);
609 showCursor(dit, false, update);
610 LYXERR(Debug::SCROLLING, "scroll to bottom");
614 // find paragraph at target position
615 int par_pos = d->scrollbarParameters_.min;
617 for (; i != int(d->par_height_.size()); ++i) {
618 par_pos += d->par_height_[i];
619 if (par_pos >= value)
623 if (par_pos < value) {
624 // It seems we didn't find the correct pit so stay on the safe side and
626 LYXERR0("scrolling position not found!");
627 scrollDocView(d->scrollbarParameters_.max, update);
631 DocIterator dit = doc_iterator_begin(&buffer_);
633 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
634 showCursor(dit, false, update);
638 // FIXME: this method is not working well.
639 void BufferView::setCursorFromScrollbar()
641 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
643 int const height = 2 * defaultRowHeight();
644 int const first = height;
645 int const last = height_ - height;
647 Cursor const & oldcur = d->cursor_;
649 switch (cursorStatus(oldcur)) {
657 int const y = getPos(oldcur).y_;
658 newy = min(last, max(y, first));
662 // We reset the cursor because cursorStatus() does not
663 // work when the cursor is within mathed.
666 tm.setCursorFromCoordinates(cur, 0, newy);
668 // update the bufferview cursor and notify insets
669 // FIXME: Care about the d->cursor_ flags to redraw if needed
670 Cursor old = d->cursor_;
672 // the DEPM call in mouseSetCursor() might have destroyed the
673 // paragraph the cursor is in.
674 bool badcursor = old.fixIfBroken();
675 badcursor |= notifyCursorLeavesOrEnters(old, d->cursor_);
677 d->cursor_.fixIfBroken();
681 Change const BufferView::getCurrentChange() const
683 if (!d->cursor_.selection())
684 return Change(Change::UNCHANGED);
686 DocIterator dit = d->cursor_.selectionBegin();
687 return dit.paragraph().lookupChange(dit.pos());
691 // this could be used elsewhere as well?
692 // FIXME: This does not work within mathed!
693 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
695 Point const p = getPos(dit);
698 if (p.y_ > workHeight())
704 void BufferView::bookmarkEditPosition()
706 // Don't eat cpu time for each keystroke
707 if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
710 d->bookmark_edit_position_ = d->cursor_.paragraph().id();
714 void BufferView::saveBookmark(unsigned int idx)
716 // tentatively save bookmark, id and pos will be used to
717 // acturately locate a bookmark in a 'live' lyx session.
718 // pit and pos will be updated with bottom level pit/pos
720 if (!buffer_.isInternal()) {
721 theSession().bookmarks().save(
723 d->cursor_.bottom().pit(),
724 d->cursor_.bottom().pos(),
725 d->cursor_.paragraph().id(),
730 // emit message signal.
731 message(_("Save bookmark"));
736 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
737 int top_id, pos_type top_pos)
739 bool success = false;
742 d->cursor_.clearSelection();
744 // if a valid par_id is given, try it first
745 // This is the case for a 'live' bookmark when unique paragraph ID
746 // is used to track bookmarks.
748 dit = buffer_.getParFromID(top_id);
750 dit.pos() = min(dit.paragraph().size(), top_pos);
751 // Some slices of the iterator may not be
752 // reachable (e.g. closed collapsable inset)
753 // so the dociterator may need to be
754 // shortened. Otherwise, setCursor may crash
755 // lyx when the cursor can not be set to these
757 size_t const n = dit.depth();
758 for (size_t i = 0; i < n; ++i)
759 if (!dit[i].inset().editable()) {
767 // if top_id == 0, or searching through top_id failed
768 // This is the case for a 'restored' bookmark when only bottom
769 // (document level) pit was saved. Because of this, bookmark
770 // restoration is inaccurate. If a bookmark was within an inset,
771 // it will be restored to the left of the outmost inset that contains
773 if (bottom_pit < int(buffer_.paragraphs().size())) {
774 dit = doc_iterator_begin(&buffer_);
776 dit.pit() = bottom_pit;
777 dit.pos() = min(bottom_pos, dit.paragraph().size());
782 // Note: only bottom (document) level pit is set.
784 // set the current font.
785 d->cursor_.setCurrentFont();
786 // To center the screen on this new position we need the
787 // paragraph position which is computed at draw() time.
788 // So we need a redraw!
789 buffer_.changed(false);
798 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
800 if (lyxrc.rtl_support) {
801 if (d->cursor_.real_current_font.isRightToLeft()) {
802 if (d->intl_.keymap == Intl::PRIMARY)
803 d->intl_.keyMapSec();
805 if (d->intl_.keymap == Intl::SECONDARY)
806 d->intl_.keyMapPrim();
810 d->intl_.getTransManager().translateAndInsert(c, t, cur);
814 int BufferView::workWidth() const
820 void BufferView::recenter()
822 showCursor(d->cursor_, true, true);
826 void BufferView::showCursor()
828 showCursor(d->cursor_, false, true);
832 void BufferView::showCursor(DocIterator const & dit,
833 bool recenter, bool update)
835 if (scrollToCursor(dit, recenter) && update) {
836 buffer_.changed(true);
837 updateHoveredInset();
842 void BufferView::scrollToCursor()
844 if (scrollToCursor(d->cursor_, false)) {
845 buffer_.changed(true);
846 updateHoveredInset();
851 bool BufferView::scrollToCursor(DocIterator const & dit, bool recenter)
853 // We are not properly started yet, delay until resizing is
858 LYXERR(Debug::SCROLLING, "recentering!");
860 CursorSlice const & bot = dit.bottom();
861 TextMetrics & tm = d->text_metrics_[bot.text()];
863 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
864 int bot_pit = bot.pit();
865 if (bot_pit > max_pit) {
866 // FIXME: Why does this happen?
867 LYXERR0("bottom pit is greater that max pit: "
868 << bot_pit << " > " << max_pit);
872 if (bot_pit == tm.first().first - 1)
873 tm.newParMetricsUp();
874 else if (bot_pit == tm.last().first + 1)
875 tm.newParMetricsDown();
877 if (tm.contains(bot_pit)) {
878 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
879 LBUFERR(!pm.rows().empty());
880 // FIXME: smooth scrolling doesn't work in mathed.
881 CursorSlice const & cs = dit.innerTextSlice();
882 int offset = coordOffset(dit).y_;
883 int ypos = pm.position() + offset;
884 Dimension const & row_dim =
885 pm.getRow(cs.pos(), dit.boundary()).dimension();
888 scrolled = scroll(ypos - height_/2);
890 // We try to visualize the whole row, if the row height is larger than
891 // the screen height, we scroll to a heuristic value of height_ / 4.
892 // FIXME: This heuristic value should be replaced by a recursive search
893 // for a row in the inset that can be visualized completely.
894 else if (row_dim.height() > height_) {
895 if (ypos < defaultRowHeight())
896 scrolled = scroll(ypos - height_ / 4);
897 else if (ypos > height_ - defaultRowHeight())
898 scrolled = scroll(ypos - 3 * height_ / 4);
901 // If the top part of the row falls of the screen, we scroll
902 // up to align the top of the row with the top of the screen.
903 else if (ypos - row_dim.ascent() < 0 && ypos < height_) {
904 int ynew = row_dim.ascent();
905 scrolled = scrollUp(ynew - ypos);
908 // If the bottom of the row falls of the screen, we scroll down.
909 else if (ypos + row_dim.descent() > height_ && ypos > 0) {
910 int ynew = height_ - row_dim.descent();
911 scrolled = scrollDown(ypos - ynew);
914 // else, nothing to do, the cursor is already visible so we just return.
915 return scrolled != 0;
918 // fix inline completion position
919 if (d->inlineCompletionPos_.fixIfBroken())
920 d->inlineCompletionPos_ = DocIterator();
922 tm.redoParagraph(bot_pit);
923 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
924 int offset = coordOffset(dit).y_;
926 d->anchor_pit_ = bot_pit;
927 CursorSlice const & cs = dit.innerTextSlice();
928 Dimension const & row_dim =
929 pm.getRow(cs.pos(), dit.boundary()).dimension();
932 d->anchor_ypos_ = height_/2;
933 else if (d->anchor_pit_ == 0)
934 d->anchor_ypos_ = offset + pm.ascent();
935 else if (d->anchor_pit_ == max_pit)
936 d->anchor_ypos_ = height_ - offset - row_dim.descent();
937 else if (offset > height_)
938 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
940 d->anchor_ypos_ = defaultRowHeight() * 2;
946 void BufferView::makeDocumentClass()
948 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
949 buffer_.params().makeDocumentClass();
950 updateDocumentClass(olddc);
954 void BufferView::updateDocumentClass(DocumentClassConstPtr olddc)
956 message(_("Converting document to new document class..."));
958 StableDocIterator backcur(d->cursor_);
959 ErrorList & el = buffer_.errorList("Class Switch");
960 cap::switchBetweenClasses(
961 olddc, buffer_.params().documentClassPtr(),
962 static_cast<InsetText &>(buffer_.inset()), el);
964 setCursor(backcur.asDocIterator(&buffer_));
966 buffer_.errors("Class Switch");
970 /** Return the change status at cursor position, taking in account the
971 * status at each level of the document iterator (a table in a deleted
972 * footnote is deleted).
973 * When \param outer is true, the top slice is not looked at.
975 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
977 size_t const depth = dit.depth() - (outer ? 1 : 0);
979 for (size_t i = 0 ; i < depth ; ++i) {
980 CursorSlice const & slice = dit[i];
981 if (!slice.inset().inMathed()
982 && slice.pos() < slice.paragraph().size()) {
983 Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
984 if (ch != Change::UNCHANGED)
988 return Change::UNCHANGED;
992 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
994 FuncCode const act = cmd.action();
996 // Can we use a readonly buffer?
997 if (buffer_.isReadonly()
998 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
999 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1000 flag.message(from_utf8(N_("Document is read-only")));
1001 flag.setEnabled(false);
1005 // Are we in a DELETED change-tracking region?
1006 if (lookupChangeType(d->cursor_, true) == Change::DELETED
1007 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1008 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1009 flag.message(from_utf8(N_("This portion of the document is deleted.")));
1010 flag.setEnabled(false);
1014 Cursor & cur = d->cursor_;
1016 if (cur.getStatus(cmd, flag))
1021 // FIXME: This is a bit problematic because we don't check if this is
1022 // a document BufferView or not for these LFUNs. We probably have to
1023 // dispatch both to currentBufferView() and, if that fails,
1024 // to documentBufferView(); same as we do now for current Buffer and
1025 // document Buffer. Ideally those LFUN should go to Buffer as they
1026 // operate on the full Buffer and the cursor is only needed either for
1027 // an Undo record or to restore a cursor position. But we don't know
1028 // how to do that inside Buffer of course.
1029 case LFUN_BUFFER_PARAMS_APPLY:
1030 case LFUN_LAYOUT_MODULES_CLEAR:
1031 case LFUN_LAYOUT_MODULE_ADD:
1032 case LFUN_LAYOUT_RELOAD:
1033 case LFUN_TEXTCLASS_APPLY:
1034 case LFUN_TEXTCLASS_LOAD:
1035 flag.setEnabled(!buffer_.isReadonly());
1039 // We do not use the LyXAction flag for readonly because Undo sets the
1040 // buffer clean/dirty status by itself.
1041 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasUndoStack());
1044 // We do not use the LyXAction flag for readonly because Redo sets the
1045 // buffer clean/dirty status by itself.
1046 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasRedoStack());
1048 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1049 case LFUN_FILE_INSERT_PLAINTEXT: {
1050 docstring const fname = cmd.argument();
1051 if (!FileName::isAbsolute(to_utf8(fname))) {
1052 flag.message(_("Absolute filename expected."));
1055 flag.setEnabled(cur.inTexted());
1058 case LFUN_FILE_INSERT:
1059 case LFUN_BOOKMARK_SAVE:
1060 // FIXME: Actually, these LFUNS should be moved to Text
1061 flag.setEnabled(cur.inTexted());
1064 case LFUN_FONT_STATE:
1065 case LFUN_LABEL_INSERT:
1066 case LFUN_INFO_INSERT:
1067 case LFUN_PARAGRAPH_GOTO:
1068 case LFUN_NOTE_NEXT:
1069 case LFUN_REFERENCE_NEXT:
1070 case LFUN_WORD_FIND:
1071 case LFUN_WORD_FIND_FORWARD:
1072 case LFUN_WORD_FIND_BACKWARD:
1073 case LFUN_WORD_REPLACE:
1076 case LFUN_MARK_TOGGLE:
1077 case LFUN_SCREEN_RECENTER:
1078 case LFUN_SCREEN_SHOW_CURSOR:
1079 case LFUN_BIBTEX_DATABASE_ADD:
1080 case LFUN_BIBTEX_DATABASE_DEL:
1081 case LFUN_STATISTICS:
1082 case LFUN_KEYMAP_OFF:
1083 case LFUN_KEYMAP_PRIMARY:
1084 case LFUN_KEYMAP_SECONDARY:
1085 case LFUN_KEYMAP_TOGGLE:
1086 flag.setEnabled(true);
1089 case LFUN_WORD_FINDADV: {
1090 FindAndReplaceOptions opt;
1091 istringstream iss(to_utf8(cmd.argument()));
1093 flag.setEnabled(opt.repl_buf_name.empty()
1094 || !buffer_.isReadonly());
1097 case LFUN_LABEL_GOTO: {
1098 flag.setEnabled(!cmd.argument().empty()
1099 || getInsetByCode<InsetRef>(cur, REF_CODE));
1103 case LFUN_CHANGES_TRACK:
1104 flag.setEnabled(true);
1105 flag.setOnOff(buffer_.params().trackChanges);
1108 case LFUN_CHANGES_OUTPUT:
1109 flag.setEnabled(true);
1110 flag.setOnOff(buffer_.params().outputChanges);
1113 case LFUN_CHANGES_MERGE:
1114 case LFUN_CHANGE_NEXT:
1115 case LFUN_CHANGE_PREVIOUS:
1116 case LFUN_ALL_CHANGES_ACCEPT:
1117 case LFUN_ALL_CHANGES_REJECT:
1118 // TODO: context-sensitive enabling of LFUNs
1119 // In principle, these command should only be enabled if there
1120 // is a change in the document. However, without proper
1121 // optimizations, this will inevitably result in poor performance.
1122 flag.setEnabled(true);
1125 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
1126 flag.setOnOff(buffer_.params().compressed);
1130 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC: {
1131 flag.setOnOff(buffer_.params().output_sync);
1135 case LFUN_SCREEN_UP:
1136 case LFUN_SCREEN_DOWN:
1138 case LFUN_SCREEN_UP_SELECT:
1139 case LFUN_SCREEN_DOWN_SELECT:
1140 case LFUN_INSET_FORALL:
1141 flag.setEnabled(true);
1144 case LFUN_LAYOUT_TABULAR:
1145 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1149 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1152 case LFUN_LAYOUT_PARAGRAPH:
1153 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1156 case LFUN_BRANCH_ADD_INSERT:
1157 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1160 case LFUN_DIALOG_SHOW_NEW_INSET:
1161 // FIXME: this is wrong, but I do not understand the
1163 if (cur.inset().lyxCode() == CAPTION_CODE)
1164 return cur.inset().getStatus(cur, cmd, flag);
1165 // FIXME we should consider passthru paragraphs too.
1166 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1169 case LFUN_CITATION_INSERT: {
1170 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1171 // FIXME: This could turn in a recursive hell.
1172 // Shouldn't we use Buffer::getStatus() instead?
1173 flag.setEnabled(lyx::getStatus(fr).enabled());
1176 case LFUN_INSET_APPLY: {
1177 string const name = cmd.getArg(0);
1178 Inset * inset = editedInset(name);
1180 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1181 if (!inset->getStatus(cur, fr, flag)) {
1182 // Every inset is supposed to handle this
1183 LASSERT(false, break);
1186 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1187 flag = lyx::getStatus(fr);
1200 Inset * BufferView::editedInset(string const & name) const
1202 map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1203 return it == d->edited_insets_.end() ? 0 : it->second;
1207 void BufferView::editInset(string const & name, Inset * inset)
1209 d->edited_insets_[name] = inset;
1213 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1215 LYXERR(Debug::ACTION, "BufferView::dispatch: cmd: " << cmd);
1217 string const argument = to_utf8(cmd.argument());
1218 Cursor & cur = d->cursor_;
1220 // Don't dispatch function that does not apply to internal buffers.
1221 if (buffer_.isInternal()
1222 && lyxaction.funcHasFlag(cmd.action(), LyXAction::NoInternal))
1225 // We'll set this back to false if need be.
1226 bool dispatched = true;
1227 buffer_.undo().beginUndoGroup();
1229 FuncCode const act = cmd.action();
1232 case LFUN_BUFFER_PARAMS_APPLY: {
1233 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
1234 cur.recordUndoFullDocument();
1235 istringstream ss(to_utf8(cmd.argument()));
1238 int const unknown_tokens = buffer_.readHeader(lex);
1239 if (unknown_tokens != 0) {
1240 LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1241 << unknown_tokens << " unknown token"
1242 << (unknown_tokens == 1 ? "" : "s"));
1244 updateDocumentClass(olddc);
1246 // We are most certainly here because of a change in the document
1247 // It is then better to make sure that all dialogs are in sync with
1248 // current document settings.
1249 dr.screenUpdate(Update::Force | Update::FitCursor);
1250 dr.forceBufferUpdate();
1254 case LFUN_LAYOUT_MODULES_CLEAR: {
1255 cur.recordUndoFullDocument();
1256 buffer_.params().clearLayoutModules();
1257 makeDocumentClass();
1258 dr.screenUpdate(Update::Force);
1259 dr.forceBufferUpdate();
1263 case LFUN_LAYOUT_MODULE_ADD: {
1264 BufferParams const & params = buffer_.params();
1265 if (!params.layoutModuleCanBeAdded(argument)) {
1266 LYXERR0("Module `" << argument <<
1267 "' cannot be added due to failed requirements or "
1268 "conflicts with installed modules.");
1271 cur.recordUndoFullDocument();
1272 buffer_.params().addLayoutModule(argument);
1273 makeDocumentClass();
1274 dr.screenUpdate(Update::Force);
1275 dr.forceBufferUpdate();
1279 case LFUN_TEXTCLASS_APPLY: {
1280 // since this shortcircuits, the second call is made only if
1282 bool const success =
1283 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1284 LayoutFileList::get().load(argument, buffer_.filePath());
1286 docstring s = bformat(_("The document class `%1$s' "
1287 "could not be loaded."), from_utf8(argument));
1288 frontend::Alert::error(_("Could not load class"), s);
1292 LayoutFile const * old_layout = buffer_.params().baseClass();
1293 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1295 if (old_layout == new_layout)
1299 // Save the old, possibly modular, layout for use in conversion.
1300 cur.recordUndoFullDocument();
1301 buffer_.params().setBaseClass(argument);
1302 makeDocumentClass();
1303 dr.screenUpdate(Update::Force);
1304 dr.forceBufferUpdate();
1308 case LFUN_TEXTCLASS_LOAD: {
1309 // since this shortcircuits, the second call is made only if
1311 bool const success =
1312 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1313 LayoutFileList::get().load(argument, buffer_.filePath());
1315 docstring s = bformat(_("The document class `%1$s' "
1316 "could not be loaded."), from_utf8(argument));
1317 frontend::Alert::error(_("Could not load class"), s);
1322 case LFUN_LAYOUT_RELOAD: {
1323 LayoutFileIndex bc = buffer_.params().baseClassID();
1324 LayoutFileList::get().reset(bc);
1325 buffer_.params().setBaseClass(bc);
1326 makeDocumentClass();
1327 dr.screenUpdate(Update::Force);
1328 dr.forceBufferUpdate();
1333 dr.setMessage(_("Undo"));
1334 cur.clearSelection();
1335 if (!cur.textUndo())
1336 dr.setMessage(_("No further undo information"));
1338 dr.screenUpdate(Update::Force | Update::FitCursor);
1339 dr.forceBufferUpdate();
1343 dr.setMessage(_("Redo"));
1344 cur.clearSelection();
1345 if (!cur.textRedo())
1346 dr.setMessage(_("No further redo information"));
1348 dr.screenUpdate(Update::Force | Update::FitCursor);
1349 dr.forceBufferUpdate();
1352 case LFUN_FONT_STATE:
1353 dr.setMessage(cur.currentState());
1356 case LFUN_BOOKMARK_SAVE:
1357 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1360 case LFUN_LABEL_GOTO: {
1361 docstring label = cmd.argument();
1362 if (label.empty()) {
1364 getInsetByCode<InsetRef>(cur, REF_CODE);
1366 label = inset->getParam("reference");
1367 // persistent=false: use temp_bookmark
1371 if (!label.empty()) {
1373 // at the moment, this is redundant, since gotoLabel will
1374 // eventually call LFUN_PARAGRAPH_GOTO, but it seems best
1376 dr.screenUpdate(Update::Force | Update::FitCursor);
1381 case LFUN_PARAGRAPH_GOTO: {
1382 int const id = convert<int>(cmd.getArg(0));
1383 int const pos = convert<int>(cmd.getArg(1));
1385 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1386 b = theBufferList().next(b)) {
1388 DocIterator dit = b->getParFromID(id);
1390 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1394 LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1395 << " found in buffer `"
1396 << b->absFileName() << "'.");
1398 if (b == &buffer_) {
1402 dr.screenUpdate(Update::Force | Update::FitCursor);
1404 // Switch to other buffer view and resend cmd
1405 lyx::dispatch(FuncRequest(
1406 LFUN_BUFFER_SWITCH, b->absFileName()));
1414 case LFUN_NOTE_NEXT:
1415 gotoInset(this, NOTE_CODE, false);
1418 case LFUN_REFERENCE_NEXT: {
1419 vector<InsetCode> tmp;
1420 tmp.push_back(LABEL_CODE);
1421 tmp.push_back(REF_CODE);
1422 gotoInset(this, tmp, true);
1426 case LFUN_CHANGES_TRACK:
1427 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1430 case LFUN_CHANGES_OUTPUT:
1431 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1432 if (buffer_.params().outputChanges) {
1433 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1434 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1435 LaTeXFeatures::isAvailable("xcolor");
1437 if (!dvipost && !xcolorulem) {
1438 Alert::warning(_("Changes not shown in LaTeX output"),
1439 _("Changes will not be highlighted in LaTeX output, "
1440 "because neither dvipost nor xcolor/ulem are installed.\n"
1441 "Please install these packages or redefine "
1442 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1443 } else if (!xcolorulem) {
1444 Alert::warning(_("Changes not shown in LaTeX output"),
1445 _("Changes will not be highlighted in LaTeX output "
1446 "when using pdflatex, because xcolor and ulem are not installed.\n"
1447 "Please install both packages or redefine "
1448 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1453 case LFUN_CHANGE_NEXT:
1454 findNextChange(this);
1455 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1456 dr.screenUpdate(Update::Force | Update::FitCursor);
1459 case LFUN_CHANGE_PREVIOUS:
1460 findPreviousChange(this);
1461 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1462 dr.screenUpdate(Update::Force | Update::FitCursor);
1465 case LFUN_CHANGES_MERGE:
1466 if (findNextChange(this) || findPreviousChange(this)) {
1467 dr.screenUpdate(Update::Force | Update::FitCursor);
1468 dr.forceBufferUpdate();
1469 showDialog("changes");
1473 case LFUN_ALL_CHANGES_ACCEPT:
1474 // select complete document
1476 cur.selHandle(true);
1477 buffer_.text().cursorBottom(cur);
1478 // accept everything in a single step to support atomic undo
1479 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1481 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1482 dr.screenUpdate(Update::Force | Update::FitCursor);
1483 dr.forceBufferUpdate();
1486 case LFUN_ALL_CHANGES_REJECT:
1487 // select complete document
1489 cur.selHandle(true);
1490 buffer_.text().cursorBottom(cur);
1491 // reject everything in a single step to support atomic undo
1492 // Note: reject does not work recursively; the user may have to repeat the operation
1493 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1495 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1496 dr.screenUpdate(Update::Force | Update::FitCursor);
1497 dr.forceBufferUpdate();
1500 case LFUN_WORD_FIND_FORWARD:
1501 case LFUN_WORD_FIND_BACKWARD: {
1502 static docstring last_search;
1503 docstring searched_string;
1505 if (!cmd.argument().empty()) {
1506 last_search = cmd.argument();
1507 searched_string = cmd.argument();
1509 searched_string = last_search;
1512 if (searched_string.empty())
1515 bool const fw = act == LFUN_WORD_FIND_FORWARD;
1516 docstring const data =
1517 find2string(searched_string, true, false, fw);
1518 bool found = lyxfind(this, FuncRequest(LFUN_WORD_FIND, data));
1520 dr.screenUpdate(Update::Force | Update::FitCursor);
1530 case LFUN_WORD_FIND: {
1531 FuncRequest req = cmd;
1532 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1533 req = d->search_request_cache_;
1534 if (req.argument().empty()) {
1535 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1538 if (lyxfind(this, req)) {
1539 dr.screenUpdate(Update::Force | Update::FitCursor);
1546 d->search_request_cache_ = req;
1550 case LFUN_WORD_REPLACE: {
1551 bool has_deleted = false;
1552 if (cur.selection()) {
1553 DocIterator beg = cur.selectionBegin();
1554 DocIterator end = cur.selectionEnd();
1555 if (beg.pit() == end.pit()) {
1556 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1557 if (!cur.inMathed() && cur.paragraph().isDeleted(p)) {
1564 if (lyxreplace(this, cmd, has_deleted)) {
1565 dr.forceBufferUpdate();
1566 dr.screenUpdate(Update::Force | Update::FitCursor);
1576 case LFUN_WORD_FINDADV: {
1577 FindAndReplaceOptions opt;
1578 istringstream iss(to_utf8(cmd.argument()));
1580 if (findAdv(this, opt)) {
1581 dr.screenUpdate(Update::Force | Update::FitCursor);
1592 cur.clearSelection();
1593 dr.setMessage(from_utf8(N_("Mark off")));
1597 cur.clearSelection();
1599 dr.setMessage(from_utf8(N_("Mark on")));
1602 case LFUN_MARK_TOGGLE:
1603 cur.setSelection(false);
1606 dr.setMessage(from_utf8(N_("Mark removed")));
1609 dr.setMessage(from_utf8(N_("Mark set")));
1614 case LFUN_SCREEN_SHOW_CURSOR:
1618 case LFUN_SCREEN_RECENTER:
1622 case LFUN_BIBTEX_DATABASE_ADD: {
1623 Cursor tmpcur = cur;
1624 findInset(tmpcur, BIBTEX_CODE, false);
1625 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1628 if (inset->addDatabase(cmd.argument())) {
1629 buffer_.invalidateBibfileCache();
1630 dr.forceBufferUpdate();
1636 case LFUN_BIBTEX_DATABASE_DEL: {
1637 Cursor tmpcur = cur;
1638 findInset(tmpcur, BIBTEX_CODE, false);
1639 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1642 if (inset->delDatabase(cmd.argument())) {
1643 buffer_.invalidateBibfileCache();
1644 dr.forceBufferUpdate();
1650 case LFUN_STATISTICS: {
1651 DocIterator from, to;
1652 if (cur.selection()) {
1653 from = cur.selectionBegin();
1654 to = cur.selectionEnd();
1656 from = doc_iterator_begin(&buffer_);
1657 to = doc_iterator_end(&buffer_);
1659 buffer_.updateStatistics(from, to);
1660 int const words = buffer_.wordCount();
1661 int const chars = buffer_.charCount(false);
1662 int const chars_blanks = buffer_.charCount(true);
1664 if (cur.selection())
1665 message = _("Statistics for the selection:");
1667 message = _("Statistics for the document:");
1670 message += bformat(_("%1$d words"), words);
1672 message += _("One word");
1674 if (chars_blanks != 1)
1675 message += bformat(_("%1$d characters (including blanks)"),
1678 message += _("One character (including blanks)");
1681 message += bformat(_("%1$d characters (excluding blanks)"),
1684 message += _("One character (excluding blanks)");
1686 Alert::information(_("Statistics"), message);
1690 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1691 // turn compression on/off
1692 buffer_.params().compressed = !buffer_.params().compressed;
1695 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
1696 buffer_.params().output_sync = !buffer_.params().output_sync;
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_);
1716 bool const in_texted = cur.inTexted();
1717 cur.setCursor(doc_iterator_begin(cur.buffer()));
1718 cur.selHandle(false);
1719 buffer_.changed(true);
1720 updateHoveredInset();
1722 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1723 true, act == LFUN_SCREEN_UP);
1724 //FIXME: what to do with cur.x_target()?
1725 bool update = in_texted && cur.bv().checkDepm(cur, old);
1728 if (update || cur.mark())
1729 dr.screenUpdate(Update::Force | Update::FitCursor);
1731 dr.forceBufferUpdate();
1736 string const scroll_type = cmd.getArg(0);
1737 int scroll_step = 0;
1738 if (scroll_type == "line")
1739 scroll_step = d->scrollbarParameters_.single_step;
1740 else if (scroll_type == "page")
1741 scroll_step = d->scrollbarParameters_.page_step;
1744 string const scroll_quantity = cmd.getArg(1);
1745 if (scroll_quantity == "up")
1746 scrollUp(scroll_step);
1747 else if (scroll_quantity == "down")
1748 scrollDown(scroll_step);
1750 int const scroll_value = convert<int>(scroll_quantity);
1752 scroll(scroll_step * scroll_value);
1754 buffer_.changed(true);
1755 updateHoveredInset();
1756 dr.forceBufferUpdate();
1760 case LFUN_SCREEN_UP_SELECT: {
1761 // FIXME: why is the algorithm different from LFUN_SCREEN_UP?
1762 cur.selHandle(true);
1763 if (isTopScreen()) {
1764 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1768 int y = getPos(cur).y_;
1769 int const ymin = y - height_ + defaultRowHeight();
1770 while (y > ymin && cur.up())
1774 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1778 case LFUN_SCREEN_DOWN_SELECT: {
1779 // FIXME: why is the algorithm different from LFUN_SCREEN_DOWN?
1780 cur.selHandle(true);
1781 if (isBottomScreen()) {
1782 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1786 int y = getPos(cur).y_;
1787 int const ymax = y + height_ - defaultRowHeight();
1788 while (y < ymax && cur.down())
1792 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1797 // This would be in Buffer class if only Cursor did not
1798 // require a bufferview
1799 case LFUN_INSET_FORALL: {
1800 docstring const name = from_utf8(cmd.getArg(0));
1801 string const commandstr = cmd.getLongArg(1);
1802 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
1804 // an arbitrary number to limit number of iterations
1805 const int max_iter = 100000;
1807 Cursor & cur = d->cursor_;
1808 Cursor const savecur = cur;
1810 if (!cur.nextInset())
1812 cur.beginUndoGroup();
1813 while(cur && iterations < max_iter) {
1814 Inset * const ins = cur.nextInset();
1817 docstring insname = ins->layoutName();
1818 while (!insname.empty()) {
1819 if (insname == name || name == from_utf8("*")) {
1821 lyx::dispatch(fr, dr);
1825 size_t const i = insname.rfind(':');
1826 if (i == string::npos)
1828 insname = insname.substr(0, i);
1830 // if we did not delete the inset, skip it
1831 if (!cur.nextInset() || cur.nextInset() == ins)
1837 dr.screenUpdate(Update::Force);
1838 dr.forceBufferUpdate();
1840 if (iterations >= max_iter) {
1842 dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
1844 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
1849 case LFUN_BRANCH_ADD_INSERT: {
1850 docstring branch_name = from_utf8(cmd.getArg(0));
1851 if (branch_name.empty())
1852 if (!Alert::askForText(branch_name, _("Branch name")) ||
1853 branch_name.empty())
1856 DispatchResult drtmp;
1857 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
1858 if (drtmp.error()) {
1859 Alert::warning(_("Branch already exists"), drtmp.message());
1862 BranchList & branch_list = buffer_.params().branchlist();
1863 vector<docstring> const branches =
1864 getVectorFromString(branch_name, branch_list.separator());
1865 for (vector<docstring>::const_iterator it = branches.begin();
1866 it != branches.end(); ++it) {
1868 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch_name));
1873 case LFUN_KEYMAP_OFF:
1874 getIntl().keyMapOn(false);
1877 case LFUN_KEYMAP_PRIMARY:
1878 getIntl().keyMapPrim();
1881 case LFUN_KEYMAP_SECONDARY:
1882 getIntl().keyMapSec();
1885 case LFUN_KEYMAP_TOGGLE:
1886 getIntl().toggleKeyMap();
1889 case LFUN_DIALOG_SHOW_NEW_INSET: {
1890 string const name = cmd.getArg(0);
1891 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1892 if (decodeInsetParam(name, data, buffer_))
1893 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1895 lyxerr << "Inset type '" << name <<
1896 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
1900 case LFUN_CITATION_INSERT: {
1901 if (argument.empty()) {
1902 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1905 // we can have one optional argument, delimited by '|'
1906 // citation-insert <key>|<text_before>
1907 // this should be enhanced to also support text_after
1908 // and citation style
1909 string arg = argument;
1911 if (contains(argument, "|")) {
1912 arg = token(argument, '|', 0);
1913 opt1 = token(argument, '|', 1);
1916 // if our cursor is directly in front of or behind a citation inset,
1917 // we will instead add the new key to it.
1918 Inset * inset = cur.nextInset();
1919 if (!inset || inset->lyxCode() != CITE_CODE)
1920 inset = cur.prevInset();
1921 if (inset && inset->lyxCode() == CITE_CODE) {
1922 InsetCitation * icite = static_cast<InsetCitation *>(inset);
1923 if (icite->addKey(arg)) {
1924 dr.forceBufferUpdate();
1925 dr.screenUpdate(Update::FitCursor | Update::SinglePar);
1927 LYXERR0("Discarding optional argument to citation-insert.");
1932 InsetCommandParams icp(CITE_CODE);
1933 icp["key"] = from_utf8(arg);
1935 icp["before"] = from_utf8(opt1);
1936 string icstr = InsetCommand::params2string(icp);
1937 FuncRequest fr(LFUN_INSET_INSERT, icstr);
1942 case LFUN_INSET_APPLY: {
1943 string const name = cmd.getArg(0);
1944 Inset * inset = editedInset(name);
1946 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1950 // put cursor in front of inset.
1951 if (!setCursorFromInset(inset)) {
1952 LASSERT(false, break);
1955 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1956 inset->dispatch(cur, fr);
1957 dr.screenUpdate(cur.result().screenUpdate());
1958 if (cur.result().needBufferUpdate())
1959 dr.forceBufferUpdate();
1964 // The change of language of buffer belongs to the Buffer class.
1965 // We have to do it here because we need a cursor for Undo.
1966 // When Undo::recordUndoBufferParams() is implemented someday
1967 // LFUN_BUFFER_LANGUAGE should be handled by the Buffer class.
1968 case LFUN_BUFFER_LANGUAGE: {
1969 Language const * oldL = buffer_.params().language;
1970 Language const * newL = languages.getLanguage(argument);
1971 if (!newL || oldL == newL)
1973 if (oldL->rightToLeft() == newL->rightToLeft()) {
1974 cur.recordUndoFullDocument();
1975 buffer_.changeLanguage(oldL, newL);
1976 cur.setCurrentFont();
1977 dr.forceBufferUpdate();
1982 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1983 case LFUN_FILE_INSERT_PLAINTEXT: {
1984 bool const as_paragraph = (act == LFUN_FILE_INSERT_PLAINTEXT_PARA);
1985 string const fname = to_utf8(cmd.argument());
1986 if (!FileName::isAbsolute(fname))
1987 dr.setMessage(_("Absolute filename expected."));
1989 insertPlaintextFile(FileName(fname), as_paragraph);
1994 // OK, so try the Buffer itself...
1995 buffer_.dispatch(cmd, dr);
1996 dispatched = dr.dispatched();
2000 buffer_.undo().endUndoGroup();
2001 dr.dispatched(dispatched);
2005 docstring const BufferView::requestSelection()
2007 Cursor & cur = d->cursor_;
2009 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
2010 if (!cur.selection()) {
2011 d->xsel_cache_.set = false;
2015 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
2016 if (!d->xsel_cache_.set ||
2017 cur.top() != d->xsel_cache_.cursor ||
2018 cur.realAnchor().top() != d->xsel_cache_.anchor)
2020 d->xsel_cache_.cursor = cur.top();
2021 d->xsel_cache_.anchor = cur.realAnchor().top();
2022 d->xsel_cache_.set = cur.selection();
2023 return cur.selectionAsString(false);
2029 void BufferView::clearSelection()
2031 d->cursor_.clearSelection();
2032 // Clear the selection buffer. Otherwise a subsequent
2033 // middle-mouse-button paste would use the selection buffer,
2034 // not the more current external selection.
2035 cap::clearSelection();
2036 d->xsel_cache_.set = false;
2037 // The buffer did not really change, but this causes the
2038 // redraw we need because we cleared the selection above.
2039 buffer_.changed(false);
2043 void BufferView::resize(int width, int height)
2045 // Update from work area
2049 // Clear the paragraph height cache.
2050 d->par_height_.clear();
2051 // Redo the metrics.
2056 Inset const * BufferView::getCoveringInset(Text const & text,
2059 TextMetrics & tm = d->text_metrics_[&text];
2060 Inset * inset = tm.checkInsetHit(x, y);
2064 if (!inset->descendable(*this))
2065 // No need to go further down if the inset is not
2069 size_t cell_number = inset->nargs();
2070 // Check all the inner cell.
2071 for (size_t i = 0; i != cell_number; ++i) {
2072 Text const * inner_text = inset->getText(i);
2075 Inset const * inset_deeper =
2076 getCoveringInset(*inner_text, x, y);
2078 return inset_deeper;
2086 void BufferView::updateHoveredInset() const
2088 // Get inset under mouse, if there is one.
2089 int const x = d->mouse_position_cache_.x_;
2090 int const y = d->mouse_position_cache_.y_;
2091 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
2093 d->clickable_inset_ = covering_inset && covering_inset->clickable(x, y);
2095 if (covering_inset == d->last_inset_)
2096 // Same inset, no need to do anything...
2099 bool need_redraw = false;
2100 if (d->last_inset_) {
2101 // Remove the hint on the last hovered inset (if any).
2102 need_redraw |= d->last_inset_->setMouseHover(this, false);
2106 if (covering_inset && covering_inset->setMouseHover(this, true)) {
2108 // Only the insets that accept the hover state, do
2109 // clear the last_inset_, so only set the last_inset_
2110 // member if the hovered setting is accepted.
2111 d->last_inset_ = covering_inset;
2115 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
2116 << d->mouse_position_cache_.x_ << ", "
2117 << d->mouse_position_cache_.y_ << ")");
2119 d->update_strategy_ = DecorationUpdate;
2121 // This event (moving without mouse click) is not passed further.
2122 // This should be changed if it is further utilized.
2123 buffer_.changed(false);
2128 void BufferView::clearLastInset(Inset * inset) const
2130 if (d->last_inset_ != inset) {
2131 LYXERR0("Wrong last_inset!");
2138 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
2140 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
2142 // This is only called for mouse related events including
2143 // LFUN_FILE_OPEN generated by drag-and-drop.
2144 FuncRequest cmd = cmd0;
2146 Cursor old = cursor();
2148 cur.push(buffer_.inset());
2149 cur.setSelection(d->cursor_.selection());
2151 // Either the inset under the cursor or the
2152 // surrounding Text will handle this event.
2154 // make sure we stay within the screen...
2155 cmd.set_y(min(max(cmd.y(), -1), height_));
2157 d->mouse_position_cache_.x_ = cmd.x();
2158 d->mouse_position_cache_.y_ = cmd.y();
2160 if (cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
2161 updateHoveredInset();
2165 // Build temporary cursor.
2166 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x(), cmd.y());
2168 // Put anchor at the same position.
2171 cur.beginUndoGroup();
2173 // Try to dispatch to an non-editable inset near this position
2174 // via the temp cursor. If the inset wishes to change the real
2175 // cursor it has to do so explicitly by using
2176 // cur.bv().cursor() = cur; (or similar)
2178 inset->dispatch(cur, cmd);
2180 // Now dispatch to the temporary cursor. If the real cursor should
2181 // be modified, the inset's dispatch has to do so explicitly.
2182 if (!inset || !cur.result().dispatched())
2187 // Notify left insets
2189 bool badcursor = old.fixIfBroken() | cur.fixIfBroken();
2190 badcursor |= notifyCursorLeavesOrEnters(old, cur);
2192 cursor().fixIfBroken();
2195 // Do we have a selection?
2196 theSelection().haveSelection(cursor().selection());
2198 if (cur.needBufferUpdate()) {
2199 cur.clearBufferUpdate();
2200 buffer().updateBuffer();
2203 // If the command has been dispatched,
2204 if (cur.result().dispatched() || cur.result().screenUpdate())
2205 processUpdateFlags(cur.result().screenUpdate());
2209 int BufferView::minVisiblePart()
2211 return 2 * defaultRowHeight();
2215 int BufferView::scroll(int y)
2218 return scrollDown(y);
2220 return scrollUp(-y);
2225 int BufferView::scrollDown(int offset)
2227 Text * text = &buffer_.text();
2228 TextMetrics & tm = d->text_metrics_[text];
2229 int const ymax = height_ + offset;
2231 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2232 int bottom_pos = last.second->position() + last.second->descent();
2233 if (lyxrc.scroll_below_document)
2234 bottom_pos += height_ - minVisiblePart();
2235 if (last.first + 1 == int(text->paragraphs().size())) {
2236 if (bottom_pos <= height_)
2238 offset = min(offset, bottom_pos - height_);
2241 if (bottom_pos > ymax)
2243 tm.newParMetricsDown();
2245 d->anchor_ypos_ -= offset;
2250 int BufferView::scrollUp(int offset)
2252 Text * text = &buffer_.text();
2253 TextMetrics & tm = d->text_metrics_[text];
2254 int ymin = - offset;
2256 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2257 int top_pos = first.second->position() - first.second->ascent();
2258 if (first.first == 0) {
2261 offset = min(offset, - top_pos);
2266 tm.newParMetricsUp();
2268 d->anchor_ypos_ += offset;
2273 void BufferView::setCursorFromRow(int row)
2277 pit_type newpit = 0;
2278 pos_type newpos = 0;
2280 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
2282 bool posvalid = (tmpid != -1);
2284 // we need to make sure that the row and position
2285 // we got back are valid, because the buffer may well
2286 // have changed since we last generated the LaTeX.
2287 DocIterator const dit = buffer_.getParFromID(tmpid);
2288 if (dit == doc_iterator_end(&buffer_))
2292 // now have to check pos.
2294 Paragraph const & par = buffer_.text().getPar(newpit);
2295 if (newpos > par.size()) {
2296 LYXERR0("Requested position no longer valid.");
2297 newpos = par.size() - 1;
2302 frontend::Alert::error(_("Inverse Search Failed"),
2303 _("Invalid position requested by inverse search.\n"
2304 "You need to update the viewed document."));
2308 buffer_.text().setCursor(d->cursor_, newpit, newpos);
2309 d->cursor_.setSelection(false);
2310 d->cursor_.resetAnchor();
2315 bool BufferView::setCursorFromInset(Inset const * inset)
2317 // are we already there?
2318 if (cursor().nextInset() == inset)
2321 // Inset is not at cursor position. Find it in the document.
2324 while (cur && cur.nextInset() != inset)
2335 void BufferView::gotoLabel(docstring const & label)
2337 ListOfBuffers bufs = buffer().allRelatives();
2338 ListOfBuffers::iterator it = bufs.begin();
2339 for (; it != bufs.end(); ++it) {
2340 Buffer const * buf = *it;
2343 Toc & toc = buf->tocBackend().toc("label");
2344 TocIterator toc_it = toc.begin();
2345 TocIterator end = toc.end();
2346 for (; toc_it != end; ++toc_it) {
2347 if (label == toc_it->str()) {
2348 lyx::dispatch(toc_it->action());
2356 TextMetrics const & BufferView::textMetrics(Text const * t) const
2358 return const_cast<BufferView *>(this)->textMetrics(t);
2362 TextMetrics & BufferView::textMetrics(Text const * t)
2365 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
2366 if (tmc_it == d->text_metrics_.end()) {
2367 tmc_it = d->text_metrics_.insert(
2368 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
2370 return tmc_it->second;
2374 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2377 return textMetrics(t).parMetrics(pit);
2381 int BufferView::workHeight() const
2387 void BufferView::setCursor(DocIterator const & dit)
2390 size_t const n = dit.depth();
2391 for (size_t i = 0; i < n; ++i)
2392 dit[i].inset().edit(d->cursor_, true);
2394 d->cursor_.setCursor(dit);
2395 d->cursor_.setSelection(false);
2397 // It seems on general grounds as if this is probably needed, but
2398 // it is not yet clear.
2399 // See bug #7394 and r38388.
2400 // d->cursor.resetAnchor();
2404 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2406 // Would be wrong to delete anything if we have a selection.
2407 if (cur.selection())
2410 bool need_anchor_change = false;
2411 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
2412 need_anchor_change);
2414 if (need_anchor_change)
2422 // we would rather not do this here, but it needs to be done before
2423 // the changed() signal is sent.
2424 buffer_.updateBuffer();
2426 buffer_.changed(true);
2431 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
2433 LASSERT(&cur.bv() == this, return false);
2436 // this event will clear selection so we save selection for
2437 // persistent selection
2438 cap::saveSelection(cursor());
2440 d->cursor_.macroModeClose();
2441 // If a macro has been finalized, the cursor might have been broken
2444 // Has the cursor just left the inset?
2445 bool const leftinset = (&d->cursor_.inset() != &cur.inset());
2447 d->cursor_.fixIfBroken();
2449 // FIXME: shift-mouse selection doesn't work well across insets.
2450 bool const do_selection =
2451 select && &d->cursor_.normalAnchor().inset() == &cur.inset();
2453 // do the dEPM magic if needed
2454 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2455 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2456 // the leftinset bool would not be necessary (badcursor instead).
2457 bool update = leftinset;
2458 if (!do_selection && d->cursor_.inTexted())
2459 update |= checkDepm(cur, d->cursor_);
2462 d->cursor_.resetAnchor();
2463 d->cursor_.setCursor(cur);
2464 d->cursor_.boundary(cur.boundary());
2466 d->cursor_.setSelection();
2468 d->cursor_.clearSelection();
2470 d->cursor_.finishUndo();
2471 d->cursor_.setCurrentFont();
2473 cur.forceBufferUpdate();
2478 void BufferView::putSelectionAt(DocIterator const & cur,
2479 int length, bool backwards)
2481 d->cursor_.clearSelection();
2487 d->cursor_.pos() += length;
2488 d->cursor_.setSelection(d->cursor_, -length);
2490 d->cursor_.setSelection(d->cursor_, length);
2495 bool BufferView::selectIfEmpty(DocIterator & cur)
2497 if (!cur.paragraph().empty())
2500 pit_type const beg_pit = cur.pit();
2502 // The paragraph associated to this item isn't
2503 // the first one, so it can be selected
2506 // We have to resort to select the space between the
2507 // end of this item and the begin of the next one
2511 // If it is the only item in the document,
2512 // nothing can be selected
2515 pit_type const end_pit = cur.pit();
2516 pos_type const end_pos = cur.pos();
2517 d->cursor_.clearSelection();
2519 d->cursor_.setCursor(cur);
2520 d->cursor_.pit() = beg_pit;
2521 d->cursor_.pos() = 0;
2522 d->cursor_.setSelection(false);
2523 d->cursor_.resetAnchor();
2524 d->cursor_.pit() = end_pit;
2525 d->cursor_.pos() = end_pos;
2526 d->cursor_.setSelection();
2531 Cursor & BufferView::cursor()
2537 Cursor const & BufferView::cursor() const
2543 pit_type BufferView::anchor_ref() const
2545 return d->anchor_pit_;
2549 bool BufferView::singleParUpdate()
2551 Text & buftext = buffer_.text();
2552 pit_type const bottom_pit = d->cursor_.bottom().pit();
2553 TextMetrics & tm = textMetrics(&buftext);
2554 int old_height = tm.parMetrics(bottom_pit).height();
2556 // make sure inline completion pointer is ok
2557 if (d->inlineCompletionPos_.fixIfBroken())
2558 d->inlineCompletionPos_ = DocIterator();
2560 // In Single Paragraph mode, rebreak only
2561 // the (main text, not inset!) paragraph containing the cursor.
2562 // (if this paragraph contains insets etc., rebreaking will
2563 // recursively descend)
2564 tm.redoParagraph(bottom_pit);
2565 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
2566 if (pm.height() != old_height)
2567 // Paragraph height has changed so we cannot proceed to
2568 // the singlePar optimisation.
2571 d->update_strategy_ = SingleParUpdate;
2573 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2574 << " y2: " << pm.position() + pm.descent()
2575 << " pit: " << bottom_pit
2576 << " singlepar: 1");
2581 void BufferView::updateMetrics()
2583 if (height_ == 0 || width_ == 0)
2586 Text & buftext = buffer_.text();
2587 pit_type const npit = int(buftext.paragraphs().size());
2589 // Clear out the position cache in case of full screen redraw,
2590 d->coord_cache_.clear();
2592 // Clear out paragraph metrics to avoid having invalid metrics
2593 // in the cache from paragraphs not relayouted below
2594 // The complete text metrics will be redone.
2595 d->text_metrics_.clear();
2597 TextMetrics & tm = textMetrics(&buftext);
2599 // make sure inline completion pointer is ok
2600 if (d->inlineCompletionPos_.fixIfBroken())
2601 d->inlineCompletionPos_ = DocIterator();
2603 if (d->anchor_pit_ >= npit)
2604 // The anchor pit must have been deleted...
2605 d->anchor_pit_ = npit - 1;
2607 // Rebreak anchor paragraph.
2608 tm.redoParagraph(d->anchor_pit_);
2609 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2612 if (d->anchor_pit_ == 0) {
2613 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2615 // Complete buffer visible? Then it's easy.
2616 if (scrollRange == 0)
2617 d->anchor_ypos_ = anchor_pm.ascent();
2619 // FIXME: Some clever handling needed to show
2620 // the _first_ paragraph up to the top if the cursor is
2621 // in the first line.
2623 anchor_pm.setPosition(d->anchor_ypos_);
2625 LYXERR(Debug::PAINTING, "metrics: "
2626 << " anchor pit = " << d->anchor_pit_
2627 << " anchor ypos = " << d->anchor_ypos_);
2629 // Redo paragraphs above anchor if necessary.
2630 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2631 // We are now just above the anchor paragraph.
2632 pit_type pit1 = d->anchor_pit_ - 1;
2633 for (; pit1 >= 0 && y1 >= 0; --pit1) {
2634 tm.redoParagraph(pit1);
2635 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2637 // Save the paragraph position in the cache.
2642 // Redo paragraphs below the anchor if necessary.
2643 int y2 = d->anchor_ypos_ + anchor_pm.descent();
2644 // We are now just below the anchor paragraph.
2645 pit_type pit2 = d->anchor_pit_ + 1;
2646 for (; pit2 < npit && y2 <= height_; ++pit2) {
2647 tm.redoParagraph(pit2);
2648 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2650 // Save the paragraph position in the cache.
2655 LYXERR(Debug::PAINTING, "Metrics: "
2656 << " anchor pit = " << d->anchor_pit_
2657 << " anchor ypos = " << d->anchor_ypos_
2660 << " pit1 = " << pit1
2661 << " pit2 = " << pit2);
2663 d->update_strategy_ = FullScreenUpdate;
2665 if (lyxerr.debugging(Debug::WORKAREA)) {
2666 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2667 d->coord_cache_.dump();
2672 void BufferView::insertLyXFile(FileName const & fname)
2674 LASSERT(d->cursor_.inTexted(), return);
2676 // Get absolute path of file and add ".lyx"
2677 // to the filename if necessary
2678 FileName filename = fileSearch(string(), fname.absFileName(), "lyx");
2680 docstring const disp_fn = makeDisplayPath(filename.absFileName());
2681 // emit message signal.
2682 message(bformat(_("Inserting document %1$s..."), disp_fn));
2685 Buffer buf(filename.absFileName(), false);
2686 if (buf.loadLyXFile() == Buffer::ReadSuccess) {
2687 ErrorList & el = buffer_.errorList("Parse");
2688 // Copy the inserted document error list into the current buffer one.
2689 el = buf.errorList("Parse");
2690 buffer_.undo().recordUndo(d->cursor_);
2691 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2692 buf.params().documentClassPtr(), el);
2693 res = _("Document %1$s inserted.");
2695 res = _("Could not insert document %1$s");
2698 buffer_.changed(true);
2699 // emit message signal.
2700 message(bformat(res, disp_fn));
2704 Point BufferView::coordOffset(DocIterator const & dit) const
2710 // Addup contribution of nested insets, from inside to outside,
2711 // keeping the outer paragraph for a special handling below
2712 for (size_t i = dit.depth() - 1; i >= 1; --i) {
2713 CursorSlice const & sl = dit[i];
2717 // get relative position inside sl.inset()
2718 sl.inset().cursorPos(*this, sl, dit.boundary() && (i + 1 == dit.depth()), xx, yy);
2720 // Make relative position inside of the edited inset relative to sl.inset()
2724 // In case of an RTL inset, the edited inset will be positioned to the left
2727 bool boundary_i = dit.boundary() && i + 1 == dit.depth();
2728 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2733 // remember width for the case that sl.inset() is positioned in an RTL inset
2734 if (i && dit[i - 1].text()) {
2735 // If this Inset is inside a Text Inset, retrieve the Dimension
2736 // from the containing text instead of using Inset::dimension() which
2737 // might not be implemented.
2738 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2739 // elimination of Inset::dim_ cache. This coordOffset() method needs
2740 // to be rewritten in light of the new design.
2741 Dimension const & dim = parMetrics(dit[i - 1].text(),
2742 dit[i - 1].pit()).insetDimension(&sl.inset());
2745 Dimension const dim = sl.inset().dimension(*this);
2749 //lyxerr << "Cursor::getPos, i: "
2750 // << i << " x: " << xx << " y: " << y << endl;
2753 // Add contribution of initial rows of outermost paragraph
2754 CursorSlice const & sl = dit[0];
2755 TextMetrics const & tm = textMetrics(sl.text());
2756 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2758 LBUFERR(!pm.rows().empty());
2759 y -= pm.rows()[0].ascent();
2761 // FIXME: document this mess
2763 if (sl.pos() > 0 && dit.depth() == 1) {
2765 if (pos && dit.boundary())
2767 // lyxerr << "coordOffset: boundary:" << dit.boundary() << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2768 rend = pm.pos2row(pos);
2770 rend = pm.pos2row(sl.pos());
2772 size_t rend = pm.pos2row(sl.pos());
2774 for (size_t rit = 0; rit != rend; ++rit)
2775 y += pm.rows()[rit].height();
2776 y += pm.rows()[rend].ascent();
2778 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2780 // Make relative position from the nested inset now bufferview absolute.
2781 int xx = bottom_tm.cursorX(dit.bottom(), dit.boundary() && dit.depth() == 1);
2784 // In the RTL case place the nested inset at the left of the cursor in
2785 // the outer paragraph
2786 bool boundary_1 = dit.boundary() && 1 == dit.depth();
2787 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2795 Point BufferView::getPos(DocIterator const & dit) const
2797 if (!paragraphVisible(dit))
2798 return Point(-1, -1);
2800 CursorSlice const & bot = dit.bottom();
2801 TextMetrics const & tm = textMetrics(bot.text());
2803 // offset from outer paragraph
2804 Point p = coordOffset(dit);
2805 p.y_ += tm.parMetrics(bot.pit()).position();
2810 bool BufferView::paragraphVisible(DocIterator const & dit) const
2812 CursorSlice const & bot = dit.bottom();
2813 TextMetrics const & tm = textMetrics(bot.text());
2815 return tm.contains(bot.pit());
2819 void BufferView::cursorPosAndHeight(Point & p, int & h) const
2821 Cursor const & cur = cursor();
2822 Font const font = cur.getFont();
2823 frontend::FontMetrics const & fm = theFontMetrics(font);
2824 int const asc = fm.maxAscent();
2825 int const des = fm.maxDescent();
2832 bool BufferView::cursorInView(Point const & p, int h) const
2834 Cursor const & cur = cursor();
2835 // does the cursor touch the screen ?
2836 if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
2842 void BufferView::draw(frontend::Painter & pain)
2844 if (height_ == 0 || width_ == 0)
2846 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2848 Text & text = buffer_.text();
2849 TextMetrics const & tm = d->text_metrics_[&text];
2850 int const y = tm.first().second->position();
2851 PainterInfo pi(this, pain);
2853 switch (d->update_strategy_) {
2855 case NoScreenUpdate:
2856 // If no screen painting is actually needed, only some the different
2857 // coordinates of insets and paragraphs needs to be updated.
2858 pi.full_repaint = true;
2859 pi.pain.setDrawingEnabled(false);
2863 case SingleParUpdate:
2864 pi.full_repaint = false;
2865 // In general, only the current row of the outermost paragraph
2866 // will be redrawn. Particular cases where selection spans
2867 // multiple paragraph are correctly detected in TextMetrics.
2871 case DecorationUpdate:
2872 // FIXME: We should also distinguish DecorationUpdate to avoid text
2873 // drawing if possible. This is not possible to do easily right now
2874 // because of the single backing pixmap.
2876 case FullScreenUpdate:
2877 // The whole screen, including insets, will be refreshed.
2878 pi.full_repaint = true;
2880 // Clear background.
2881 pain.fillRectangle(0, 0, width_, height_,
2882 pi.backgroundColor(&buffer_.inset()));
2887 // and possibly grey out below
2888 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2889 int const y2 = lastpm.second->position() + lastpm.second->descent();
2892 Color color = buffer().isInternal()
2893 ? Color_background : Color_bottomarea;
2894 pain.fillRectangle(0, y2, width_, height_ - y2, color);
2898 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
2900 // The scrollbar needs an update.
2903 // Normalize anchor for next time
2904 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2905 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2906 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2907 ParagraphMetrics const & pm = tm.parMetrics(pit);
2908 if (pm.position() + pm.descent() > 0) {
2909 d->anchor_pit_ = pit;
2910 d->anchor_ypos_ = pm.position();
2914 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2915 << " anchor ypos = " << d->anchor_ypos_);
2919 void BufferView::message(docstring const & msg)
2922 d->gui_->message(msg);
2926 void BufferView::showDialog(string const & name)
2929 d->gui_->showDialog(name, string());
2933 void BufferView::showDialog(string const & name,
2934 string const & data, Inset * inset)
2937 d->gui_->showDialog(name, data, inset);
2941 void BufferView::updateDialog(string const & name, string const & data)
2944 d->gui_->updateDialog(name, data);
2948 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2954 // FIXME: Move this out of BufferView again
2955 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2957 if (!fname.isReadableFile()) {
2958 docstring const error = from_ascii(strerror(errno));
2959 docstring const file = makeDisplayPath(fname.absFileName(), 50);
2960 docstring const text =
2961 bformat(_("Could not read the specified document\n"
2962 "%1$s\ndue to the error: %2$s"), file, error);
2963 Alert::error(_("Could not read file"), text);
2967 if (!fname.isReadableFile()) {
2968 docstring const file = makeDisplayPath(fname.absFileName(), 50);
2969 docstring const text =
2970 bformat(_("%1$s\n is not readable."), file);
2971 Alert::error(_("Could not open file"), text);
2975 // FIXME UNICODE: We don't know the encoding of the file
2976 docstring file_content = fname.fileContents("UTF-8");
2977 if (file_content.empty()) {
2978 Alert::error(_("Reading not UTF-8 encoded file"),
2979 _("The file is not UTF-8 encoded.\n"
2980 "It will be read as local 8Bit-encoded.\n"
2981 "If this does not give the correct result\n"
2982 "then please change the encoding of the file\n"
2983 "to UTF-8 with a program other than LyX.\n"));
2984 file_content = fname.fileContents("local8bit");
2987 return normalize_c(file_content);
2991 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2993 docstring const tmpstr = contentsOfPlaintextFile(f);
2998 Cursor & cur = cursor();
2999 cap::replaceSelection(cur);
3000 buffer_.undo().recordUndo(cur);
3002 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
3004 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
3006 buffer_.changed(true);
3010 docstring const & BufferView::inlineCompletion() const
3012 return d->inlineCompletion_;
3016 size_t const & BufferView::inlineCompletionUniqueChars() const
3018 return d->inlineCompletionUniqueChars_;
3022 DocIterator const & BufferView::inlineCompletionPos() const
3024 return d->inlineCompletionPos_;
3028 void BufferView::resetInlineCompletionPos()
3030 d->inlineCompletionPos_ = DocIterator();
3034 bool samePar(DocIterator const & a, DocIterator const & b)
3036 if (a.empty() && b.empty())
3038 if (a.empty() || b.empty())
3040 if (a.depth() != b.depth())
3042 return &a.innerParagraph() == &b.innerParagraph();
3046 void BufferView::setInlineCompletion(Cursor const & cur, DocIterator const & pos,
3047 docstring const & completion, size_t uniqueChars)
3049 uniqueChars = min(completion.size(), uniqueChars);
3050 bool changed = d->inlineCompletion_ != completion
3051 || d->inlineCompletionUniqueChars_ != uniqueChars;
3052 bool singlePar = true;
3053 d->inlineCompletion_ = completion;
3054 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
3056 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
3059 DocIterator const & old = d->inlineCompletionPos_;
3061 //lyxerr << "inlineCompletionPos changed" << std::endl;
3062 // old or pos are in another paragraph?
3063 if ((!samePar(cur, pos) && !pos.empty())
3064 || (!samePar(cur, old) && !old.empty())) {
3066 //lyxerr << "different paragraph" << std::endl;
3068 d->inlineCompletionPos_ = pos;
3073 if (singlePar && !(cur.result().screenUpdate() & Update::Force))
3074 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
3076 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::Force);
3081 bool BufferView::clickableInset() const
3083 return d->clickable_inset_;