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_BRANCH_ADD_INSERT:
1083 case LFUN_KEYMAP_OFF:
1084 case LFUN_KEYMAP_PRIMARY:
1085 case LFUN_KEYMAP_SECONDARY:
1086 case LFUN_KEYMAP_TOGGLE:
1087 flag.setEnabled(true);
1090 case LFUN_WORD_FINDADV: {
1091 FindAndReplaceOptions opt;
1092 istringstream iss(to_utf8(cmd.argument()));
1094 flag.setEnabled(opt.repl_buf_name.empty()
1095 || !buffer_.isReadonly());
1098 case LFUN_LABEL_GOTO: {
1099 flag.setEnabled(!cmd.argument().empty()
1100 || getInsetByCode<InsetRef>(cur, REF_CODE));
1104 case LFUN_CHANGES_TRACK:
1105 flag.setEnabled(true);
1106 flag.setOnOff(buffer_.params().trackChanges);
1109 case LFUN_CHANGES_OUTPUT:
1110 flag.setEnabled(true);
1111 flag.setOnOff(buffer_.params().outputChanges);
1114 case LFUN_CHANGES_MERGE:
1115 case LFUN_CHANGE_NEXT:
1116 case LFUN_CHANGE_PREVIOUS:
1117 case LFUN_ALL_CHANGES_ACCEPT:
1118 case LFUN_ALL_CHANGES_REJECT:
1119 // TODO: context-sensitive enabling of LFUNs
1120 // In principle, these command should only be enabled if there
1121 // is a change in the document. However, without proper
1122 // optimizations, this will inevitably result in poor performance.
1123 flag.setEnabled(true);
1126 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
1127 flag.setOnOff(buffer_.params().compressed);
1131 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC: {
1132 flag.setOnOff(buffer_.params().output_sync);
1136 case LFUN_SCREEN_UP:
1137 case LFUN_SCREEN_DOWN:
1139 case LFUN_SCREEN_UP_SELECT:
1140 case LFUN_SCREEN_DOWN_SELECT:
1141 case LFUN_INSET_FORALL:
1142 flag.setEnabled(true);
1145 case LFUN_LAYOUT_TABULAR:
1146 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1150 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1153 case LFUN_LAYOUT_PARAGRAPH:
1154 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1157 case LFUN_DIALOG_SHOW_NEW_INSET:
1158 // FIXME: this is wrong, but I do not understand the
1160 if (cur.inset().lyxCode() == CAPTION_CODE)
1161 return cur.inset().getStatus(cur, cmd, flag);
1162 // FIXME we should consider passthru paragraphs too.
1163 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1166 case LFUN_CITATION_INSERT: {
1167 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1168 // FIXME: This could turn in a recursive hell.
1169 // Shouldn't we use Buffer::getStatus() instead?
1170 flag.setEnabled(lyx::getStatus(fr).enabled());
1173 case LFUN_INSET_APPLY: {
1174 string const name = cmd.getArg(0);
1175 Inset * inset = editedInset(name);
1177 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1178 if (!inset->getStatus(cur, fr, flag)) {
1179 // Every inset is supposed to handle this
1180 LASSERT(false, break);
1183 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1184 flag = lyx::getStatus(fr);
1197 Inset * BufferView::editedInset(string const & name) const
1199 map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1200 return it == d->edited_insets_.end() ? 0 : it->second;
1204 void BufferView::editInset(string const & name, Inset * inset)
1206 d->edited_insets_[name] = inset;
1210 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1212 LYXERR(Debug::ACTION, "BufferView::dispatch: cmd: " << cmd);
1214 string const argument = to_utf8(cmd.argument());
1215 Cursor & cur = d->cursor_;
1217 // Don't dispatch function that does not apply to internal buffers.
1218 if (buffer_.isInternal()
1219 && lyxaction.funcHasFlag(cmd.action(), LyXAction::NoInternal))
1222 // We'll set this back to false if need be.
1223 bool dispatched = true;
1224 buffer_.undo().beginUndoGroup();
1226 FuncCode const act = cmd.action();
1229 case LFUN_BUFFER_PARAMS_APPLY: {
1230 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
1231 cur.recordUndoFullDocument();
1232 istringstream ss(to_utf8(cmd.argument()));
1235 int const unknown_tokens = buffer_.readHeader(lex);
1236 if (unknown_tokens != 0) {
1237 LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1238 << unknown_tokens << " unknown token"
1239 << (unknown_tokens == 1 ? "" : "s"));
1241 updateDocumentClass(olddc);
1243 // We are most certainly here because of a change in the document
1244 // It is then better to make sure that all dialogs are in sync with
1245 // current document settings.
1246 dr.screenUpdate(Update::Force | Update::FitCursor);
1247 dr.forceBufferUpdate();
1251 case LFUN_LAYOUT_MODULES_CLEAR: {
1252 cur.recordUndoFullDocument();
1253 buffer_.params().clearLayoutModules();
1254 makeDocumentClass();
1255 dr.screenUpdate(Update::Force);
1256 dr.forceBufferUpdate();
1260 case LFUN_LAYOUT_MODULE_ADD: {
1261 BufferParams const & params = buffer_.params();
1262 if (!params.layoutModuleCanBeAdded(argument)) {
1263 LYXERR0("Module `" << argument <<
1264 "' cannot be added due to failed requirements or "
1265 "conflicts with installed modules.");
1268 cur.recordUndoFullDocument();
1269 buffer_.params().addLayoutModule(argument);
1270 makeDocumentClass();
1271 dr.screenUpdate(Update::Force);
1272 dr.forceBufferUpdate();
1276 case LFUN_TEXTCLASS_APPLY: {
1277 // since this shortcircuits, the second call is made only if
1279 bool const success =
1280 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1281 LayoutFileList::get().load(argument, buffer_.filePath());
1283 docstring s = bformat(_("The document class `%1$s' "
1284 "could not be loaded."), from_utf8(argument));
1285 frontend::Alert::error(_("Could not load class"), s);
1289 LayoutFile const * old_layout = buffer_.params().baseClass();
1290 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1292 if (old_layout == new_layout)
1296 // Save the old, possibly modular, layout for use in conversion.
1297 cur.recordUndoFullDocument();
1298 buffer_.params().setBaseClass(argument);
1299 makeDocumentClass();
1300 dr.screenUpdate(Update::Force);
1301 dr.forceBufferUpdate();
1305 case LFUN_TEXTCLASS_LOAD: {
1306 // since this shortcircuits, the second call is made only if
1308 bool const success =
1309 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1310 LayoutFileList::get().load(argument, buffer_.filePath());
1312 docstring s = bformat(_("The document class `%1$s' "
1313 "could not be loaded."), from_utf8(argument));
1314 frontend::Alert::error(_("Could not load class"), s);
1319 case LFUN_LAYOUT_RELOAD: {
1320 LayoutFileIndex bc = buffer_.params().baseClassID();
1321 LayoutFileList::get().reset(bc);
1322 buffer_.params().setBaseClass(bc);
1323 makeDocumentClass();
1324 dr.screenUpdate(Update::Force);
1325 dr.forceBufferUpdate();
1330 dr.setMessage(_("Undo"));
1331 cur.clearSelection();
1332 if (!cur.textUndo())
1333 dr.setMessage(_("No further undo information"));
1335 dr.screenUpdate(Update::Force | Update::FitCursor);
1336 dr.forceBufferUpdate();
1340 dr.setMessage(_("Redo"));
1341 cur.clearSelection();
1342 if (!cur.textRedo())
1343 dr.setMessage(_("No further redo information"));
1345 dr.screenUpdate(Update::Force | Update::FitCursor);
1346 dr.forceBufferUpdate();
1349 case LFUN_FONT_STATE:
1350 dr.setMessage(cur.currentState());
1353 case LFUN_BOOKMARK_SAVE:
1354 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1357 case LFUN_LABEL_GOTO: {
1358 docstring label = cmd.argument();
1359 if (label.empty()) {
1361 getInsetByCode<InsetRef>(cur, REF_CODE);
1363 label = inset->getParam("reference");
1364 // persistent=false: use temp_bookmark
1368 if (!label.empty()) {
1370 // at the moment, this is redundant, since gotoLabel will
1371 // eventually call LFUN_PARAGRAPH_GOTO, but it seems best
1373 dr.screenUpdate(Update::Force | Update::FitCursor);
1378 case LFUN_PARAGRAPH_GOTO: {
1379 int const id = convert<int>(cmd.getArg(0));
1380 int const pos = convert<int>(cmd.getArg(1));
1382 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1383 b = theBufferList().next(b)) {
1385 DocIterator dit = b->getParFromID(id);
1387 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1391 LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1392 << " found in buffer `"
1393 << b->absFileName() << "'.");
1395 if (b == &buffer_) {
1399 dr.screenUpdate(Update::Force | Update::FitCursor);
1401 // Switch to other buffer view and resend cmd
1402 lyx::dispatch(FuncRequest(
1403 LFUN_BUFFER_SWITCH, b->absFileName()));
1411 case LFUN_NOTE_NEXT:
1412 gotoInset(this, NOTE_CODE, false);
1415 case LFUN_REFERENCE_NEXT: {
1416 vector<InsetCode> tmp;
1417 tmp.push_back(LABEL_CODE);
1418 tmp.push_back(REF_CODE);
1419 gotoInset(this, tmp, true);
1423 case LFUN_CHANGES_TRACK:
1424 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1427 case LFUN_CHANGES_OUTPUT:
1428 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1429 if (buffer_.params().outputChanges) {
1430 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1431 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1432 LaTeXFeatures::isAvailable("xcolor");
1434 if (!dvipost && !xcolorulem) {
1435 Alert::warning(_("Changes not shown in LaTeX output"),
1436 _("Changes will not be highlighted in LaTeX output, "
1437 "because neither dvipost nor xcolor/ulem are installed.\n"
1438 "Please install these packages or redefine "
1439 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1440 } else if (!xcolorulem) {
1441 Alert::warning(_("Changes not shown in LaTeX output"),
1442 _("Changes will not be highlighted in LaTeX output "
1443 "when using pdflatex, because xcolor and ulem are not installed.\n"
1444 "Please install both packages or redefine "
1445 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1450 case LFUN_CHANGE_NEXT:
1451 findNextChange(this);
1452 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1453 dr.screenUpdate(Update::Force | Update::FitCursor);
1456 case LFUN_CHANGE_PREVIOUS:
1457 findPreviousChange(this);
1458 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1459 dr.screenUpdate(Update::Force | Update::FitCursor);
1462 case LFUN_CHANGES_MERGE:
1463 if (findNextChange(this) || findPreviousChange(this)) {
1464 dr.screenUpdate(Update::Force | Update::FitCursor);
1465 dr.forceBufferUpdate();
1466 showDialog("changes");
1470 case LFUN_ALL_CHANGES_ACCEPT:
1471 // select complete document
1473 cur.selHandle(true);
1474 buffer_.text().cursorBottom(cur);
1475 // accept everything in a single step to support atomic undo
1476 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1478 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1479 dr.screenUpdate(Update::Force | Update::FitCursor);
1480 dr.forceBufferUpdate();
1483 case LFUN_ALL_CHANGES_REJECT:
1484 // select complete document
1486 cur.selHandle(true);
1487 buffer_.text().cursorBottom(cur);
1488 // reject everything in a single step to support atomic undo
1489 // Note: reject does not work recursively; the user may have to repeat the operation
1490 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1492 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1493 dr.screenUpdate(Update::Force | Update::FitCursor);
1494 dr.forceBufferUpdate();
1497 case LFUN_WORD_FIND_FORWARD:
1498 case LFUN_WORD_FIND_BACKWARD: {
1499 static docstring last_search;
1500 docstring searched_string;
1502 if (!cmd.argument().empty()) {
1503 last_search = cmd.argument();
1504 searched_string = cmd.argument();
1506 searched_string = last_search;
1509 if (searched_string.empty())
1512 bool const fw = act == LFUN_WORD_FIND_FORWARD;
1513 docstring const data =
1514 find2string(searched_string, true, false, fw);
1515 bool found = lyxfind(this, FuncRequest(LFUN_WORD_FIND, data));
1517 dr.screenUpdate(Update::Force | Update::FitCursor);
1521 case LFUN_WORD_FIND: {
1522 FuncRequest req = cmd;
1523 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1524 req = d->search_request_cache_;
1525 if (req.argument().empty()) {
1526 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1529 if (lyxfind(this, req))
1530 dr.screenUpdate(Update::Force | Update::FitCursor);
1532 message(_("String not found."));
1533 d->search_request_cache_ = req;
1537 case LFUN_WORD_REPLACE: {
1538 bool has_deleted = false;
1539 if (cur.selection()) {
1540 DocIterator beg = cur.selectionBegin();
1541 DocIterator end = cur.selectionEnd();
1542 if (beg.pit() == end.pit()) {
1543 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1544 if (!cur.inMathed() && cur.paragraph().isDeleted(p)) {
1551 if (lyxreplace(this, cmd, has_deleted)) {
1552 dr.forceBufferUpdate();
1553 dr.screenUpdate(Update::Force | Update::FitCursor);
1558 case LFUN_WORD_FINDADV: {
1559 FindAndReplaceOptions opt;
1560 istringstream iss(to_utf8(cmd.argument()));
1562 if (findAdv(this, opt)) {
1563 dr.screenUpdate(Update::Force | Update::FitCursor);
1574 cur.clearSelection();
1575 dr.setMessage(from_utf8(N_("Mark off")));
1579 cur.clearSelection();
1581 dr.setMessage(from_utf8(N_("Mark on")));
1584 case LFUN_MARK_TOGGLE:
1585 cur.setSelection(false);
1588 dr.setMessage(from_utf8(N_("Mark removed")));
1591 dr.setMessage(from_utf8(N_("Mark set")));
1596 case LFUN_SCREEN_SHOW_CURSOR:
1600 case LFUN_SCREEN_RECENTER:
1604 case LFUN_BIBTEX_DATABASE_ADD: {
1605 Cursor tmpcur = cur;
1606 findInset(tmpcur, BIBTEX_CODE, false);
1607 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1610 if (inset->addDatabase(cmd.argument())) {
1611 buffer_.invalidateBibfileCache();
1612 dr.forceBufferUpdate();
1618 case LFUN_BIBTEX_DATABASE_DEL: {
1619 Cursor tmpcur = cur;
1620 findInset(tmpcur, BIBTEX_CODE, false);
1621 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1624 if (inset->delDatabase(cmd.argument())) {
1625 buffer_.invalidateBibfileCache();
1626 dr.forceBufferUpdate();
1632 case LFUN_STATISTICS: {
1633 DocIterator from, to;
1634 if (cur.selection()) {
1635 from = cur.selectionBegin();
1636 to = cur.selectionEnd();
1638 from = doc_iterator_begin(&buffer_);
1639 to = doc_iterator_end(&buffer_);
1641 buffer_.updateStatistics(from, to);
1642 int const words = buffer_.wordCount();
1643 int const chars = buffer_.charCount(false);
1644 int const chars_blanks = buffer_.charCount(true);
1646 if (cur.selection())
1647 message = _("Statistics for the selection:");
1649 message = _("Statistics for the document:");
1652 message += bformat(_("%1$d words"), words);
1654 message += _("One word");
1656 if (chars_blanks != 1)
1657 message += bformat(_("%1$d characters (including blanks)"),
1660 message += _("One character (including blanks)");
1663 message += bformat(_("%1$d characters (excluding blanks)"),
1666 message += _("One character (excluding blanks)");
1668 Alert::information(_("Statistics"), message);
1672 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1673 // turn compression on/off
1674 buffer_.params().compressed = !buffer_.params().compressed;
1677 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
1678 buffer_.params().output_sync = !buffer_.params().output_sync;
1681 case LFUN_SCREEN_UP:
1682 case LFUN_SCREEN_DOWN: {
1683 Point p = getPos(cur);
1684 // This code has been commented out to enable to scroll down a
1685 // document, even if there are large insets in it (see bug #5465).
1686 /*if (p.y_ < 0 || p.y_ > height_) {
1687 // The cursor is off-screen so recenter before proceeding.
1691 int const scrolled = scroll(act == LFUN_SCREEN_UP
1692 ? -height_ : height_);
1693 if (act == LFUN_SCREEN_UP && scrolled > -height_)
1695 if (act == LFUN_SCREEN_DOWN && scrolled < height_)
1696 p = Point(width_, height_);
1698 bool const in_texted = cur.inTexted();
1699 cur.setCursor(doc_iterator_begin(cur.buffer()));
1700 cur.selHandle(false);
1701 buffer_.changed(true);
1702 updateHoveredInset();
1704 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1705 true, act == LFUN_SCREEN_UP);
1706 //FIXME: what to do with cur.x_target()?
1707 bool update = in_texted && cur.bv().checkDepm(cur, old);
1710 if (update || cur.mark())
1711 dr.screenUpdate(Update::Force | Update::FitCursor);
1713 dr.forceBufferUpdate();
1718 string const scroll_type = cmd.getArg(0);
1719 int scroll_step = 0;
1720 if (scroll_type == "line")
1721 scroll_step = d->scrollbarParameters_.single_step;
1722 else if (scroll_type == "page")
1723 scroll_step = d->scrollbarParameters_.page_step;
1726 string const scroll_quantity = cmd.getArg(1);
1727 if (scroll_quantity == "up")
1728 scrollUp(scroll_step);
1729 else if (scroll_quantity == "down")
1730 scrollDown(scroll_step);
1732 int const scroll_value = convert<int>(scroll_quantity);
1734 scroll(scroll_step * scroll_value);
1736 buffer_.changed(true);
1737 updateHoveredInset();
1738 dr.forceBufferUpdate();
1742 case LFUN_SCREEN_UP_SELECT: {
1743 // FIXME: why is the algorithm different from LFUN_SCREEN_UP?
1744 cur.selHandle(true);
1745 if (isTopScreen()) {
1746 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1750 int y = getPos(cur).y_;
1751 int const ymin = y - height_ + defaultRowHeight();
1752 while (y > ymin && cur.up())
1756 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1760 case LFUN_SCREEN_DOWN_SELECT: {
1761 // FIXME: why is the algorithm different from LFUN_SCREEN_DOWN?
1762 cur.selHandle(true);
1763 if (isBottomScreen()) {
1764 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1768 int y = getPos(cur).y_;
1769 int const ymax = y + height_ - defaultRowHeight();
1770 while (y < ymax && cur.down())
1774 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1779 // This would be in Buffer class if only Cursor did not
1780 // require a bufferview
1781 case LFUN_INSET_FORALL: {
1782 docstring const name = from_utf8(cmd.getArg(0));
1783 string const commandstr = cmd.getLongArg(1);
1784 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
1786 // an arbitrary number to limit number of iterations
1787 const int max_iter = 100000;
1789 Cursor & cur = d->cursor_;
1790 Cursor const savecur = cur;
1792 if (!cur.nextInset())
1794 cur.beginUndoGroup();
1795 while(cur && iterations < max_iter) {
1796 Inset * const ins = cur.nextInset();
1799 docstring insname = ins->layoutName();
1800 while (!insname.empty()) {
1801 if (insname == name || name == from_utf8("*")) {
1803 lyx::dispatch(fr, dr);
1807 size_t const i = insname.rfind(':');
1808 if (i == string::npos)
1810 insname = insname.substr(0, i);
1812 // if we did not delete the inset, skip it
1813 if (!cur.nextInset() || cur.nextInset() == ins)
1819 dr.screenUpdate(Update::Force);
1820 dr.forceBufferUpdate();
1822 if (iterations >= max_iter) {
1824 dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
1826 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
1831 case LFUN_BRANCH_ADD_INSERT: {
1832 docstring branch_name = from_utf8(cmd.getArg(0));
1833 if (branch_name.empty())
1834 if (!Alert::askForText(branch_name, _("Branch name")) ||
1835 branch_name.empty())
1838 DispatchResult drtmp;
1839 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
1840 if (drtmp.error()) {
1841 Alert::warning(_("Branch already exists"), drtmp.message());
1844 BranchList & branch_list = buffer_.params().branchlist();
1845 vector<docstring> const branches =
1846 getVectorFromString(branch_name, branch_list.separator());
1847 for (vector<docstring>::const_iterator it = branches.begin();
1848 it != branches.end(); ++it) {
1850 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch_name));
1855 case LFUN_KEYMAP_OFF:
1856 getIntl().keyMapOn(false);
1859 case LFUN_KEYMAP_PRIMARY:
1860 getIntl().keyMapPrim();
1863 case LFUN_KEYMAP_SECONDARY:
1864 getIntl().keyMapSec();
1867 case LFUN_KEYMAP_TOGGLE:
1868 getIntl().toggleKeyMap();
1871 case LFUN_DIALOG_SHOW_NEW_INSET: {
1872 string const name = cmd.getArg(0);
1873 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1874 if (decodeInsetParam(name, data, buffer_))
1875 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1877 lyxerr << "Inset type '" << name <<
1878 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
1882 case LFUN_CITATION_INSERT: {
1883 if (argument.empty()) {
1884 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1887 // we can have one optional argument, delimited by '|'
1888 // citation-insert <key>|<text_before>
1889 // this should be enhanced to also support text_after
1890 // and citation style
1891 string arg = argument;
1893 if (contains(argument, "|")) {
1894 arg = token(argument, '|', 0);
1895 opt1 = token(argument, '|', 1);
1898 // if our cursor is directly in front of or behind a citation inset,
1899 // we will instead add the new key to it.
1900 Inset * inset = cur.nextInset();
1901 if (!inset || inset->lyxCode() != CITE_CODE)
1902 inset = cur.prevInset();
1903 if (inset && inset->lyxCode() == CITE_CODE) {
1904 InsetCitation * icite = static_cast<InsetCitation *>(inset);
1905 if (icite->addKey(arg)) {
1906 dr.forceBufferUpdate();
1907 dr.screenUpdate(Update::FitCursor | Update::SinglePar);
1909 LYXERR0("Discarding optional argument to citation-insert.");
1914 InsetCommandParams icp(CITE_CODE);
1915 icp["key"] = from_utf8(arg);
1917 icp["before"] = from_utf8(opt1);
1918 string icstr = InsetCommand::params2string(icp);
1919 FuncRequest fr(LFUN_INSET_INSERT, icstr);
1924 case LFUN_INSET_APPLY: {
1925 string const name = cmd.getArg(0);
1926 Inset * inset = editedInset(name);
1928 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1932 // put cursor in front of inset.
1933 if (!setCursorFromInset(inset)) {
1934 LASSERT(false, break);
1937 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1938 inset->dispatch(cur, fr);
1939 dr.screenUpdate(cur.result().screenUpdate());
1940 if (cur.result().needBufferUpdate())
1941 dr.forceBufferUpdate();
1946 // The change of language of buffer belongs to the Buffer class.
1947 // We have to do it here because we need a cursor for Undo.
1948 // When Undo::recordUndoBufferParams() is implemented someday
1949 // LFUN_BUFFER_LANGUAGE should be handled by the Buffer class.
1950 case LFUN_BUFFER_LANGUAGE: {
1951 Language const * oldL = buffer_.params().language;
1952 Language const * newL = languages.getLanguage(argument);
1953 if (!newL || oldL == newL)
1955 if (oldL->rightToLeft() == newL->rightToLeft()) {
1956 cur.recordUndoFullDocument();
1957 buffer_.changeLanguage(oldL, newL);
1958 cur.setCurrentFont();
1959 dr.forceBufferUpdate();
1964 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1965 case LFUN_FILE_INSERT_PLAINTEXT: {
1966 bool const as_paragraph = (act == LFUN_FILE_INSERT_PLAINTEXT_PARA);
1967 string const fname = to_utf8(cmd.argument());
1968 if (!FileName::isAbsolute(fname))
1969 dr.setMessage(_("Absolute filename expected."));
1971 insertPlaintextFile(FileName(fname), as_paragraph);
1976 // OK, so try the Buffer itself...
1977 buffer_.dispatch(cmd, dr);
1978 dispatched = dr.dispatched();
1982 buffer_.undo().endUndoGroup();
1983 dr.dispatched(dispatched);
1987 docstring const BufferView::requestSelection()
1989 Cursor & cur = d->cursor_;
1991 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
1992 if (!cur.selection()) {
1993 d->xsel_cache_.set = false;
1997 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
1998 if (!d->xsel_cache_.set ||
1999 cur.top() != d->xsel_cache_.cursor ||
2000 cur.realAnchor().top() != d->xsel_cache_.anchor)
2002 d->xsel_cache_.cursor = cur.top();
2003 d->xsel_cache_.anchor = cur.realAnchor().top();
2004 d->xsel_cache_.set = cur.selection();
2005 return cur.selectionAsString(false);
2011 void BufferView::clearSelection()
2013 d->cursor_.clearSelection();
2014 // Clear the selection buffer. Otherwise a subsequent
2015 // middle-mouse-button paste would use the selection buffer,
2016 // not the more current external selection.
2017 cap::clearSelection();
2018 d->xsel_cache_.set = false;
2019 // The buffer did not really change, but this causes the
2020 // redraw we need because we cleared the selection above.
2021 buffer_.changed(false);
2025 void BufferView::resize(int width, int height)
2027 // Update from work area
2031 // Clear the paragraph height cache.
2032 d->par_height_.clear();
2033 // Redo the metrics.
2038 Inset const * BufferView::getCoveringInset(Text const & text,
2041 TextMetrics & tm = d->text_metrics_[&text];
2042 Inset * inset = tm.checkInsetHit(x, y);
2046 if (!inset->descendable(*this))
2047 // No need to go further down if the inset is not
2051 size_t cell_number = inset->nargs();
2052 // Check all the inner cell.
2053 for (size_t i = 0; i != cell_number; ++i) {
2054 Text const * inner_text = inset->getText(i);
2057 Inset const * inset_deeper =
2058 getCoveringInset(*inner_text, x, y);
2060 return inset_deeper;
2068 void BufferView::updateHoveredInset() const
2070 // Get inset under mouse, if there is one.
2071 int const x = d->mouse_position_cache_.x_;
2072 int const y = d->mouse_position_cache_.y_;
2073 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
2075 d->clickable_inset_ = covering_inset && covering_inset->clickable(x, y);
2077 if (covering_inset == d->last_inset_)
2078 // Same inset, no need to do anything...
2081 bool need_redraw = false;
2082 if (d->last_inset_) {
2083 // Remove the hint on the last hovered inset (if any).
2084 need_redraw |= d->last_inset_->setMouseHover(this, false);
2088 if (covering_inset && covering_inset->setMouseHover(this, true)) {
2090 // Only the insets that accept the hover state, do
2091 // clear the last_inset_, so only set the last_inset_
2092 // member if the hovered setting is accepted.
2093 d->last_inset_ = covering_inset;
2097 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
2098 << d->mouse_position_cache_.x_ << ", "
2099 << d->mouse_position_cache_.y_ << ")");
2101 d->update_strategy_ = DecorationUpdate;
2103 // This event (moving without mouse click) is not passed further.
2104 // This should be changed if it is further utilized.
2105 buffer_.changed(false);
2110 void BufferView::clearLastInset(Inset * inset) const
2112 if (d->last_inset_ != inset) {
2113 LYXERR0("Wrong last_inset!");
2120 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
2122 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
2124 // This is only called for mouse related events including
2125 // LFUN_FILE_OPEN generated by drag-and-drop.
2126 FuncRequest cmd = cmd0;
2128 Cursor old = cursor();
2130 cur.push(buffer_.inset());
2131 cur.setSelection(d->cursor_.selection());
2133 // Either the inset under the cursor or the
2134 // surrounding Text will handle this event.
2136 // make sure we stay within the screen...
2137 cmd.set_y(min(max(cmd.y(), -1), height_));
2139 d->mouse_position_cache_.x_ = cmd.x();
2140 d->mouse_position_cache_.y_ = cmd.y();
2142 if (cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
2143 updateHoveredInset();
2147 // Build temporary cursor.
2148 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x(), cmd.y());
2150 // Put anchor at the same position.
2153 cur.beginUndoGroup();
2155 // Try to dispatch to an non-editable inset near this position
2156 // via the temp cursor. If the inset wishes to change the real
2157 // cursor it has to do so explicitly by using
2158 // cur.bv().cursor() = cur; (or similar)
2160 inset->dispatch(cur, cmd);
2162 // Now dispatch to the temporary cursor. If the real cursor should
2163 // be modified, the inset's dispatch has to do so explicitly.
2164 if (!inset || !cur.result().dispatched())
2169 // Notify left insets
2171 bool badcursor = old.fixIfBroken() | cur.fixIfBroken();
2172 badcursor |= notifyCursorLeavesOrEnters(old, cur);
2174 cursor().fixIfBroken();
2177 // Do we have a selection?
2178 theSelection().haveSelection(cursor().selection());
2180 if (cur.needBufferUpdate()) {
2181 cur.clearBufferUpdate();
2182 buffer().updateBuffer();
2185 // If the command has been dispatched,
2186 if (cur.result().dispatched() || cur.result().screenUpdate())
2187 processUpdateFlags(cur.result().screenUpdate());
2191 int BufferView::minVisiblePart()
2193 return 2 * defaultRowHeight();
2197 int BufferView::scroll(int y)
2200 return scrollDown(y);
2202 return scrollUp(-y);
2207 int BufferView::scrollDown(int offset)
2209 Text * text = &buffer_.text();
2210 TextMetrics & tm = d->text_metrics_[text];
2211 int const ymax = height_ + offset;
2213 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2214 int bottom_pos = last.second->position() + last.second->descent();
2215 if (lyxrc.scroll_below_document)
2216 bottom_pos += height_ - minVisiblePart();
2217 if (last.first + 1 == int(text->paragraphs().size())) {
2218 if (bottom_pos <= height_)
2220 offset = min(offset, bottom_pos - height_);
2223 if (bottom_pos > ymax)
2225 tm.newParMetricsDown();
2227 d->anchor_ypos_ -= offset;
2232 int BufferView::scrollUp(int offset)
2234 Text * text = &buffer_.text();
2235 TextMetrics & tm = d->text_metrics_[text];
2236 int ymin = - offset;
2238 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2239 int top_pos = first.second->position() - first.second->ascent();
2240 if (first.first == 0) {
2243 offset = min(offset, - top_pos);
2248 tm.newParMetricsUp();
2250 d->anchor_ypos_ += offset;
2255 void BufferView::setCursorFromRow(int row)
2259 pit_type newpit = 0;
2260 pos_type newpos = 0;
2262 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
2264 bool posvalid = (tmpid != -1);
2266 // we need to make sure that the row and position
2267 // we got back are valid, because the buffer may well
2268 // have changed since we last generated the LaTeX.
2269 DocIterator const dit = buffer_.getParFromID(tmpid);
2270 if (dit == doc_iterator_end(&buffer_))
2274 // now have to check pos.
2276 Paragraph const & par = buffer_.text().getPar(newpit);
2277 if (newpos > par.size()) {
2278 LYXERR0("Requested position no longer valid.");
2279 newpos = par.size() - 1;
2284 frontend::Alert::error(_("Inverse Search Failed"),
2285 _("Invalid position requested by inverse search.\n"
2286 "You need to update the viewed document."));
2290 buffer_.text().setCursor(d->cursor_, newpit, newpos);
2291 d->cursor_.setSelection(false);
2292 d->cursor_.resetAnchor();
2297 bool BufferView::setCursorFromInset(Inset const * inset)
2299 // are we already there?
2300 if (cursor().nextInset() == inset)
2303 // Inset is not at cursor position. Find it in the document.
2306 while (cur && cur.nextInset() != inset)
2317 void BufferView::gotoLabel(docstring const & label)
2319 ListOfBuffers bufs = buffer().allRelatives();
2320 ListOfBuffers::iterator it = bufs.begin();
2321 for (; it != bufs.end(); ++it) {
2322 Buffer const * buf = *it;
2325 Toc & toc = buf->tocBackend().toc("label");
2326 TocIterator toc_it = toc.begin();
2327 TocIterator end = toc.end();
2328 for (; toc_it != end; ++toc_it) {
2329 if (label == toc_it->str()) {
2330 lyx::dispatch(toc_it->action());
2338 TextMetrics const & BufferView::textMetrics(Text const * t) const
2340 return const_cast<BufferView *>(this)->textMetrics(t);
2344 TextMetrics & BufferView::textMetrics(Text const * t)
2347 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
2348 if (tmc_it == d->text_metrics_.end()) {
2349 tmc_it = d->text_metrics_.insert(
2350 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
2352 return tmc_it->second;
2356 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2359 return textMetrics(t).parMetrics(pit);
2363 int BufferView::workHeight() const
2369 void BufferView::setCursor(DocIterator const & dit)
2372 size_t const n = dit.depth();
2373 for (size_t i = 0; i < n; ++i)
2374 dit[i].inset().edit(d->cursor_, true);
2376 d->cursor_.setCursor(dit);
2377 d->cursor_.setSelection(false);
2379 // It seems on general grounds as if this is probably needed, but
2380 // it is not yet clear.
2381 // See bug #7394 and r38388.
2382 // d->cursor.resetAnchor();
2386 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2388 // Would be wrong to delete anything if we have a selection.
2389 if (cur.selection())
2392 bool need_anchor_change = false;
2393 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
2394 need_anchor_change);
2396 if (need_anchor_change)
2404 // we would rather not do this here, but it needs to be done before
2405 // the changed() signal is sent.
2406 buffer_.updateBuffer();
2408 buffer_.changed(true);
2413 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
2415 LASSERT(&cur.bv() == this, return false);
2418 // this event will clear selection so we save selection for
2419 // persistent selection
2420 cap::saveSelection(cursor());
2422 d->cursor_.macroModeClose();
2423 // If a macro has been finalized, the cursor might have been broken
2426 // Has the cursor just left the inset?
2427 bool const leftinset = (&d->cursor_.inset() != &cur.inset());
2429 d->cursor_.fixIfBroken();
2431 // FIXME: shift-mouse selection doesn't work well across insets.
2432 bool const do_selection =
2433 select && &d->cursor_.normalAnchor().inset() == &cur.inset();
2435 // do the dEPM magic if needed
2436 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2437 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2438 // the leftinset bool would not be necessary (badcursor instead).
2439 bool update = leftinset;
2440 if (!do_selection && d->cursor_.inTexted())
2441 update |= checkDepm(cur, d->cursor_);
2444 d->cursor_.resetAnchor();
2445 d->cursor_.setCursor(cur);
2446 d->cursor_.boundary(cur.boundary());
2448 d->cursor_.setSelection();
2450 d->cursor_.clearSelection();
2452 d->cursor_.finishUndo();
2453 d->cursor_.setCurrentFont();
2455 cur.forceBufferUpdate();
2460 void BufferView::putSelectionAt(DocIterator const & cur,
2461 int length, bool backwards)
2463 d->cursor_.clearSelection();
2469 d->cursor_.pos() += length;
2470 d->cursor_.setSelection(d->cursor_, -length);
2472 d->cursor_.setSelection(d->cursor_, length);
2477 bool BufferView::selectIfEmpty(DocIterator & cur)
2479 if (!cur.paragraph().empty())
2482 pit_type const beg_pit = cur.pit();
2484 // The paragraph associated to this item isn't
2485 // the first one, so it can be selected
2488 // We have to resort to select the space between the
2489 // end of this item and the begin of the next one
2493 // If it is the only item in the document,
2494 // nothing can be selected
2497 pit_type const end_pit = cur.pit();
2498 pos_type const end_pos = cur.pos();
2499 d->cursor_.clearSelection();
2501 d->cursor_.setCursor(cur);
2502 d->cursor_.pit() = beg_pit;
2503 d->cursor_.pos() = 0;
2504 d->cursor_.setSelection(false);
2505 d->cursor_.resetAnchor();
2506 d->cursor_.pit() = end_pit;
2507 d->cursor_.pos() = end_pos;
2508 d->cursor_.setSelection();
2513 Cursor & BufferView::cursor()
2519 Cursor const & BufferView::cursor() const
2525 pit_type BufferView::anchor_ref() const
2527 return d->anchor_pit_;
2531 bool BufferView::singleParUpdate()
2533 Text & buftext = buffer_.text();
2534 pit_type const bottom_pit = d->cursor_.bottom().pit();
2535 TextMetrics & tm = textMetrics(&buftext);
2536 int old_height = tm.parMetrics(bottom_pit).height();
2538 // make sure inline completion pointer is ok
2539 if (d->inlineCompletionPos_.fixIfBroken())
2540 d->inlineCompletionPos_ = DocIterator();
2542 // In Single Paragraph mode, rebreak only
2543 // the (main text, not inset!) paragraph containing the cursor.
2544 // (if this paragraph contains insets etc., rebreaking will
2545 // recursively descend)
2546 tm.redoParagraph(bottom_pit);
2547 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
2548 if (pm.height() != old_height)
2549 // Paragraph height has changed so we cannot proceed to
2550 // the singlePar optimisation.
2553 d->update_strategy_ = SingleParUpdate;
2555 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2556 << " y2: " << pm.position() + pm.descent()
2557 << " pit: " << bottom_pit
2558 << " singlepar: 1");
2563 void BufferView::updateMetrics()
2565 if (height_ == 0 || width_ == 0)
2568 Text & buftext = buffer_.text();
2569 pit_type const npit = int(buftext.paragraphs().size());
2571 // Clear out the position cache in case of full screen redraw,
2572 d->coord_cache_.clear();
2574 // Clear out paragraph metrics to avoid having invalid metrics
2575 // in the cache from paragraphs not relayouted below
2576 // The complete text metrics will be redone.
2577 d->text_metrics_.clear();
2579 TextMetrics & tm = textMetrics(&buftext);
2581 // make sure inline completion pointer is ok
2582 if (d->inlineCompletionPos_.fixIfBroken())
2583 d->inlineCompletionPos_ = DocIterator();
2585 if (d->anchor_pit_ >= npit)
2586 // The anchor pit must have been deleted...
2587 d->anchor_pit_ = npit - 1;
2589 // Rebreak anchor paragraph.
2590 tm.redoParagraph(d->anchor_pit_);
2591 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2594 if (d->anchor_pit_ == 0) {
2595 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2597 // Complete buffer visible? Then it's easy.
2598 if (scrollRange == 0)
2599 d->anchor_ypos_ = anchor_pm.ascent();
2601 // FIXME: Some clever handling needed to show
2602 // the _first_ paragraph up to the top if the cursor is
2603 // in the first line.
2605 anchor_pm.setPosition(d->anchor_ypos_);
2607 LYXERR(Debug::PAINTING, "metrics: "
2608 << " anchor pit = " << d->anchor_pit_
2609 << " anchor ypos = " << d->anchor_ypos_);
2611 // Redo paragraphs above anchor if necessary.
2612 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2613 // We are now just above the anchor paragraph.
2614 pit_type pit1 = d->anchor_pit_ - 1;
2615 for (; pit1 >= 0 && y1 >= 0; --pit1) {
2616 tm.redoParagraph(pit1);
2617 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2619 // Save the paragraph position in the cache.
2624 // Redo paragraphs below the anchor if necessary.
2625 int y2 = d->anchor_ypos_ + anchor_pm.descent();
2626 // We are now just below the anchor paragraph.
2627 pit_type pit2 = d->anchor_pit_ + 1;
2628 for (; pit2 < npit && y2 <= height_; ++pit2) {
2629 tm.redoParagraph(pit2);
2630 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2632 // Save the paragraph position in the cache.
2637 LYXERR(Debug::PAINTING, "Metrics: "
2638 << " anchor pit = " << d->anchor_pit_
2639 << " anchor ypos = " << d->anchor_ypos_
2642 << " pit1 = " << pit1
2643 << " pit2 = " << pit2);
2645 d->update_strategy_ = FullScreenUpdate;
2647 if (lyxerr.debugging(Debug::WORKAREA)) {
2648 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2649 d->coord_cache_.dump();
2654 void BufferView::insertLyXFile(FileName const & fname)
2656 LASSERT(d->cursor_.inTexted(), return);
2658 // Get absolute path of file and add ".lyx"
2659 // to the filename if necessary
2660 FileName filename = fileSearch(string(), fname.absFileName(), "lyx");
2662 docstring const disp_fn = makeDisplayPath(filename.absFileName());
2663 // emit message signal.
2664 message(bformat(_("Inserting document %1$s..."), disp_fn));
2667 Buffer buf(filename.absFileName(), false);
2668 if (buf.loadLyXFile() == Buffer::ReadSuccess) {
2669 ErrorList & el = buffer_.errorList("Parse");
2670 // Copy the inserted document error list into the current buffer one.
2671 el = buf.errorList("Parse");
2672 buffer_.undo().recordUndo(d->cursor_);
2673 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2674 buf.params().documentClassPtr(), el);
2675 res = _("Document %1$s inserted.");
2677 res = _("Could not insert document %1$s");
2680 buffer_.changed(true);
2681 // emit message signal.
2682 message(bformat(res, disp_fn));
2686 Point BufferView::coordOffset(DocIterator const & dit) const
2692 // Addup contribution of nested insets, from inside to outside,
2693 // keeping the outer paragraph for a special handling below
2694 for (size_t i = dit.depth() - 1; i >= 1; --i) {
2695 CursorSlice const & sl = dit[i];
2699 // get relative position inside sl.inset()
2700 sl.inset().cursorPos(*this, sl, dit.boundary() && (i + 1 == dit.depth()), xx, yy);
2702 // Make relative position inside of the edited inset relative to sl.inset()
2706 // In case of an RTL inset, the edited inset will be positioned to the left
2709 bool boundary_i = dit.boundary() && i + 1 == dit.depth();
2710 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2715 // remember width for the case that sl.inset() is positioned in an RTL inset
2716 if (i && dit[i - 1].text()) {
2717 // If this Inset is inside a Text Inset, retrieve the Dimension
2718 // from the containing text instead of using Inset::dimension() which
2719 // might not be implemented.
2720 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2721 // elimination of Inset::dim_ cache. This coordOffset() method needs
2722 // to be rewritten in light of the new design.
2723 Dimension const & dim = parMetrics(dit[i - 1].text(),
2724 dit[i - 1].pit()).insetDimension(&sl.inset());
2727 Dimension const dim = sl.inset().dimension(*this);
2731 //lyxerr << "Cursor::getPos, i: "
2732 // << i << " x: " << xx << " y: " << y << endl;
2735 // Add contribution of initial rows of outermost paragraph
2736 CursorSlice const & sl = dit[0];
2737 TextMetrics const & tm = textMetrics(sl.text());
2738 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2740 LBUFERR(!pm.rows().empty());
2741 y -= pm.rows()[0].ascent();
2743 // FIXME: document this mess
2745 if (sl.pos() > 0 && dit.depth() == 1) {
2747 if (pos && dit.boundary())
2749 // lyxerr << "coordOffset: boundary:" << dit.boundary() << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2750 rend = pm.pos2row(pos);
2752 rend = pm.pos2row(sl.pos());
2754 size_t rend = pm.pos2row(sl.pos());
2756 for (size_t rit = 0; rit != rend; ++rit)
2757 y += pm.rows()[rit].height();
2758 y += pm.rows()[rend].ascent();
2760 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2762 // Make relative position from the nested inset now bufferview absolute.
2763 int xx = bottom_tm.cursorX(dit.bottom(), dit.boundary() && dit.depth() == 1);
2766 // In the RTL case place the nested inset at the left of the cursor in
2767 // the outer paragraph
2768 bool boundary_1 = dit.boundary() && 1 == dit.depth();
2769 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2777 Point BufferView::getPos(DocIterator const & dit) const
2779 if (!paragraphVisible(dit))
2780 return Point(-1, -1);
2782 CursorSlice const & bot = dit.bottom();
2783 TextMetrics const & tm = textMetrics(bot.text());
2785 // offset from outer paragraph
2786 Point p = coordOffset(dit);
2787 p.y_ += tm.parMetrics(bot.pit()).position();
2792 bool BufferView::paragraphVisible(DocIterator const & dit) const
2794 CursorSlice const & bot = dit.bottom();
2795 TextMetrics const & tm = textMetrics(bot.text());
2797 return tm.contains(bot.pit());
2801 void BufferView::cursorPosAndHeight(Point & p, int & h) const
2803 Cursor const & cur = cursor();
2804 Font const font = cur.getFont();
2805 frontend::FontMetrics const & fm = theFontMetrics(font);
2806 int const asc = fm.maxAscent();
2807 int const des = fm.maxDescent();
2814 bool BufferView::cursorInView(Point const & p, int h) const
2816 Cursor const & cur = cursor();
2817 // does the cursor touch the screen ?
2818 if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
2824 void BufferView::draw(frontend::Painter & pain)
2826 if (height_ == 0 || width_ == 0)
2828 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2830 Text & text = buffer_.text();
2831 TextMetrics const & tm = d->text_metrics_[&text];
2832 int const y = tm.first().second->position();
2833 PainterInfo pi(this, pain);
2835 switch (d->update_strategy_) {
2837 case NoScreenUpdate:
2838 // If no screen painting is actually needed, only some the different
2839 // coordinates of insets and paragraphs needs to be updated.
2840 pi.full_repaint = true;
2841 pi.pain.setDrawingEnabled(false);
2845 case SingleParUpdate:
2846 pi.full_repaint = false;
2847 // In general, only the current row of the outermost paragraph
2848 // will be redrawn. Particular cases where selection spans
2849 // multiple paragraph are correctly detected in TextMetrics.
2853 case DecorationUpdate:
2854 // FIXME: We should also distinguish DecorationUpdate to avoid text
2855 // drawing if possible. This is not possible to do easily right now
2856 // because of the single backing pixmap.
2858 case FullScreenUpdate:
2859 // The whole screen, including insets, will be refreshed.
2860 pi.full_repaint = true;
2862 // Clear background.
2863 pain.fillRectangle(0, 0, width_, height_,
2864 pi.backgroundColor(&buffer_.inset()));
2869 // and possibly grey out below
2870 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2871 int const y2 = lastpm.second->position() + lastpm.second->descent();
2874 Color color = buffer().isInternal()
2875 ? Color_background : Color_bottomarea;
2876 pain.fillRectangle(0, y2, width_, height_ - y2, color);
2880 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
2882 // The scrollbar needs an update.
2885 // Normalize anchor for next time
2886 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2887 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2888 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2889 ParagraphMetrics const & pm = tm.parMetrics(pit);
2890 if (pm.position() + pm.descent() > 0) {
2891 d->anchor_pit_ = pit;
2892 d->anchor_ypos_ = pm.position();
2896 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2897 << " anchor ypos = " << d->anchor_ypos_);
2901 void BufferView::message(docstring const & msg)
2904 d->gui_->message(msg);
2908 void BufferView::showDialog(string const & name)
2911 d->gui_->showDialog(name, string());
2915 void BufferView::showDialog(string const & name,
2916 string const & data, Inset * inset)
2919 d->gui_->showDialog(name, data, inset);
2923 void BufferView::updateDialog(string const & name, string const & data)
2926 d->gui_->updateDialog(name, data);
2930 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2936 // FIXME: Move this out of BufferView again
2937 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2939 if (!fname.isReadableFile()) {
2940 docstring const error = from_ascii(strerror(errno));
2941 docstring const file = makeDisplayPath(fname.absFileName(), 50);
2942 docstring const text =
2943 bformat(_("Could not read the specified document\n"
2944 "%1$s\ndue to the error: %2$s"), file, error);
2945 Alert::error(_("Could not read file"), text);
2949 if (!fname.isReadableFile()) {
2950 docstring const file = makeDisplayPath(fname.absFileName(), 50);
2951 docstring const text =
2952 bformat(_("%1$s\n is not readable."), file);
2953 Alert::error(_("Could not open file"), text);
2957 // FIXME UNICODE: We don't know the encoding of the file
2958 docstring file_content = fname.fileContents("UTF-8");
2959 if (file_content.empty()) {
2960 Alert::error(_("Reading not UTF-8 encoded file"),
2961 _("The file is not UTF-8 encoded.\n"
2962 "It will be read as local 8Bit-encoded.\n"
2963 "If this does not give the correct result\n"
2964 "then please change the encoding of the file\n"
2965 "to UTF-8 with a program other than LyX.\n"));
2966 file_content = fname.fileContents("local8bit");
2969 return normalize_c(file_content);
2973 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2975 docstring const tmpstr = contentsOfPlaintextFile(f);
2980 Cursor & cur = cursor();
2981 cap::replaceSelection(cur);
2982 buffer_.undo().recordUndo(cur);
2984 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
2986 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
2988 buffer_.changed(true);
2992 docstring const & BufferView::inlineCompletion() const
2994 return d->inlineCompletion_;
2998 size_t const & BufferView::inlineCompletionUniqueChars() const
3000 return d->inlineCompletionUniqueChars_;
3004 DocIterator const & BufferView::inlineCompletionPos() const
3006 return d->inlineCompletionPos_;
3010 void BufferView::resetInlineCompletionPos()
3012 d->inlineCompletionPos_ = DocIterator();
3016 bool samePar(DocIterator const & a, DocIterator const & b)
3018 if (a.empty() && b.empty())
3020 if (a.empty() || b.empty())
3022 if (a.depth() != b.depth())
3024 return &a.innerParagraph() == &b.innerParagraph();
3028 void BufferView::setInlineCompletion(Cursor const & cur, DocIterator const & pos,
3029 docstring const & completion, size_t uniqueChars)
3031 uniqueChars = min(completion.size(), uniqueChars);
3032 bool changed = d->inlineCompletion_ != completion
3033 || d->inlineCompletionUniqueChars_ != uniqueChars;
3034 bool singlePar = true;
3035 d->inlineCompletion_ = completion;
3036 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
3038 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
3041 DocIterator const & old = d->inlineCompletionPos_;
3043 //lyxerr << "inlineCompletionPos changed" << std::endl;
3044 // old or pos are in another paragraph?
3045 if ((!samePar(cur, pos) && !pos.empty())
3046 || (!samePar(cur, old) && !old.empty())) {
3048 //lyxerr << "different paragraph" << std::endl;
3050 d->inlineCompletionPos_ = pos;
3055 if (singlePar && !(cur.result().screenUpdate() & Update::Force))
3056 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
3058 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::Force);
3063 bool BufferView::clickableInset() const
3065 return d->clickable_inset_;