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/InsetCommand.h" // ChangeRefs
58 #include "insets/InsetExternal.h"
59 #include "insets/InsetGraphics.h"
60 #include "insets/InsetNote.h"
61 #include "insets/InsetRef.h"
62 #include "insets/InsetText.h"
64 #include "frontends/alert.h"
65 #include "frontends/Application.h"
66 #include "frontends/Delegates.h"
67 #include "frontends/FontMetrics.h"
68 #include "frontends/Painter.h"
69 #include "frontends/Selection.h"
71 #include "support/convert.h"
72 #include "support/debug.h"
73 #include "support/ExceptionMessage.h"
74 #include "support/filetools.h"
75 #include "support/gettext.h"
76 #include "support/lassert.h"
77 #include "support/lstrings.h"
78 #include "support/Package.h"
79 #include "support/types.h"
89 using namespace lyx::support;
93 namespace Alert = frontend::Alert;
97 /// Return an inset of this class if it exists at the current cursor position
99 T * getInsetByCode(Cursor const & cur, InsetCode code)
101 DocIterator it = cur;
102 Inset * inset = it.nextInset();
103 if (inset && inset->lyxCode() == code)
104 return static_cast<T*>(inset);
108 /// Note that comparing contents can only be used for InsetCommand
109 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
110 docstring const & contents)
112 DocIterator tmpdit = dit;
115 Inset const * inset = tmpdit.nextInset();
117 bool const valid_code = std::find(codes.begin(), codes.end(),
118 inset->lyxCode()) != codes.end();
119 InsetCommand const * ic = inset->asInsetCommand();
120 bool const same_or_no_contents = contents.empty()
121 || (ic && (ic->getFirstNonOptParam() == contents));
123 if (valid_code && same_or_no_contents) {
128 tmpdit.forwardInset();
135 /// Looks for next inset with one of the given codes.
136 /// Note that same_content can only be used for InsetCommand
137 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
141 DocIterator tmpdit = dit;
142 tmpdit.forwardInset();
146 Inset const * inset = tmpdit.nextInset();
147 if (same_content && inset) {
148 InsetCommand const * ic = inset->asInsetCommand();
150 bool const valid_code = std::find(codes.begin(), codes.end(),
151 ic->lyxCode()) != codes.end();
153 contents = ic->getFirstNonOptParam();
157 if (!findNextInset(tmpdit, codes, contents)) {
158 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
159 Inset * inset = &tmpdit.bottom().inset();
160 tmpdit = doc_iterator_begin(&inset->buffer(), inset);
161 if (!findNextInset(tmpdit, codes, contents))
173 /// Looks for next inset with the given code
174 void findInset(DocIterator & dit, InsetCode code, bool same_content)
176 findInset(dit, vector<InsetCode>(1, code), same_content);
180 /// Moves cursor to the next inset with one of the given codes.
181 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
184 Cursor tmpcur = bv->cursor();
185 if (!findInset(tmpcur, codes, same_content)) {
186 bv->cursor().message(_("No more insets"));
190 tmpcur.clearSelection();
191 bv->setCursor(tmpcur);
196 /// Moves cursor to the next inset with given code.
197 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
199 gotoInset(bv, vector<InsetCode>(1, code), same_content);
203 /// A map from a Text to the associated text metrics
204 typedef map<Text const *, TextMetrics> TextMetricsCache;
206 enum ScreenUpdateStrategy {
216 /////////////////////////////////////////////////////////////////////
220 /////////////////////////////////////////////////////////////////////
222 struct BufferView::Private
224 Private(BufferView & bv): wh_(0), cursor_(bv),
225 anchor_pit_(0), anchor_ypos_(0),
226 inlineCompletionUniqueChars_(0),
227 last_inset_(0), clickable_inset_(false),
228 mouse_position_cache_(),
229 bookmark_edit_position_(-1), gui_(0)
233 ScrollbarParameters scrollbarParameters_;
235 ScreenUpdateStrategy update_strategy_;
237 CoordCache coord_cache_;
239 /// Estimated average par height for scrollbar.
241 /// this is used to handle XSelection events in the right manner.
250 pit_type anchor_pit_;
254 vector<int> par_height_;
257 DocIterator inlineCompletionPos_;
259 docstring inlineCompletion_;
261 size_t inlineCompletionUniqueChars_;
263 /// keyboard mapping object.
266 /// last visited inset.
267 /** kept to send setMouseHover(false).
268 * Not owned, so don't delete.
270 Inset const * last_inset_;
271 /// are we hovering something that we can click
272 bool clickable_inset_;
274 /// position of the mouse at the time of the last mouse move
275 /// This is used to update the hovering status of inset in
276 /// cases where the buffer is scrolled, but the mouse didn't move.
277 Point mouse_position_cache_;
279 // cache for id of the paragraph which was edited the last time
280 int bookmark_edit_position_;
282 mutable TextMetricsCache text_metrics_;
285 /** Not owned, so don't delete.
287 frontend::GuiBufferViewDelegate * gui_;
289 /// Cache for Find Next
290 FuncRequest search_request_cache_;
293 map<string, Inset *> edited_insets_;
297 BufferView::BufferView(Buffer & buf)
298 : width_(0), height_(0), full_screen_(false), buffer_(buf),
299 d(new Private(*this))
301 d->xsel_cache_.set = false;
302 d->intl_.initKeyMapper(lyxrc.use_kbmap);
304 d->cursor_.setBuffer(&buf);
305 d->cursor_.push(buffer_.inset());
306 d->cursor_.resetAnchor();
307 d->cursor_.setCurrentFont();
309 buffer_.updatePreviews();
313 BufferView::~BufferView()
315 // current buffer is going to be switched-off, save cursor pos
316 // Ideally, the whole cursor stack should be saved, but session
317 // currently can only handle bottom (whole document) level pit and pos.
318 // That is to say, if a cursor is in a nested inset, it will be
319 // restore to the left of the top level inset.
320 LastFilePosSection::FilePos fp;
321 fp.pit = d->cursor_.bottom().pit();
322 fp.pos = d->cursor_.bottom().pos();
323 theSession().lastFilePos().save(buffer_.fileName(), fp);
326 d->last_inset_->setMouseHover(this, false);
332 int BufferView::rightMargin() const
334 // The additional test for the case the outliner is opened.
336 !lyxrc.full_screen_limit ||
337 width_ < lyxrc.full_screen_width + 20)
340 return (width_ - lyxrc.full_screen_width) / 2;
344 int BufferView::leftMargin() const
346 return rightMargin();
350 bool BufferView::isTopScreen() const
352 return d->scrollbarParameters_.position == d->scrollbarParameters_.min;
356 bool BufferView::isBottomScreen() const
358 return d->scrollbarParameters_.position == d->scrollbarParameters_.max;
362 Intl & BufferView::getIntl()
368 Intl const & BufferView::getIntl() const
374 CoordCache & BufferView::coordCache()
376 return d->coord_cache_;
380 CoordCache const & BufferView::coordCache() const
382 return d->coord_cache_;
386 Buffer & BufferView::buffer()
392 Buffer const & BufferView::buffer() const
398 bool BufferView::fitCursor()
400 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
401 frontend::FontMetrics const & fm =
402 theFontMetrics(d->cursor_.getFont().fontInfo());
403 int const asc = fm.maxAscent();
404 int const des = fm.maxDescent();
405 Point const p = getPos(d->cursor_);
406 if (p.y_ - asc >= 0 && p.y_ + des < height_)
413 void BufferView::processUpdateFlags(Update::flags flags)
415 // This is close to a hot-path.
416 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
417 << "[fitcursor = " << (flags & Update::FitCursor)
418 << ", forceupdate = " << (flags & Update::Force)
419 << ", singlepar = " << (flags & Update::SinglePar)
420 << "] buffer: " << &buffer_);
422 // FIXME Does this really need doing here? It's done in updateBuffer, and
423 // if the Buffer doesn't need updating, then do the macros?
424 buffer_.updateMacros();
426 // Now do the first drawing step if needed. This consists on updating
427 // the CoordCache in updateMetrics().
428 // The second drawing step is done in WorkArea::redraw() if needed.
430 // Case when no explicit update is requested.
432 // no need to redraw anything.
433 d->update_strategy_ = NoScreenUpdate;
437 if (flags == Update::Decoration) {
438 d->update_strategy_ = DecorationUpdate;
439 buffer_.changed(false);
443 if (flags == Update::FitCursor
444 || flags == (Update::Decoration | Update::FitCursor)) {
445 // tell the frontend to update the screen if needed.
450 if (flags & Update::Decoration) {
451 d->update_strategy_ = DecorationUpdate;
452 buffer_.changed(false);
455 // no screen update is needed.
456 d->update_strategy_ = NoScreenUpdate;
460 bool const full_metrics = flags & Update::Force || !singleParUpdate();
463 // We have to update the full screen metrics.
466 if (!(flags & Update::FitCursor)) {
467 // Nothing to do anymore. Trigger a redraw and return
468 buffer_.changed(false);
472 // updateMetrics() does not update paragraph position
473 // This is done at draw() time. So we need a redraw!
474 buffer_.changed(false);
477 // The cursor is off screen so ensure it is visible.
482 updateHoveredInset();
486 void BufferView::updateScrollbar()
488 if (height_ == 0 && width_ == 0)
491 // We prefer fixed size line scrolling.
492 d->scrollbarParameters_.single_step = defaultRowHeight();
493 // We prefer full screen page scrolling.
494 d->scrollbarParameters_.page_step = height_;
496 Text & t = buffer_.text();
497 TextMetrics & tm = d->text_metrics_[&t];
499 LYXERR(Debug::GUI, " Updating scrollbar: height: "
500 << t.paragraphs().size()
501 << " curr par: " << d->cursor_.bottom().pit()
502 << " default height " << defaultRowHeight());
504 size_t const parsize = t.paragraphs().size();
505 if (d->par_height_.size() != parsize) {
506 d->par_height_.clear();
507 // FIXME: We assume a default paragraph height of 2 rows. This
508 // should probably be pondered with the screen width.
509 d->par_height_.resize(parsize, defaultRowHeight() * 2);
512 // Look at paragraph heights on-screen
513 pair<pit_type, ParagraphMetrics const *> first = tm.first();
514 pair<pit_type, ParagraphMetrics const *> last = tm.last();
515 for (pit_type pit = first.first; pit <= last.first; ++pit) {
516 d->par_height_[pit] = tm.parMetrics(pit).height();
517 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
518 << d->par_height_[pit]);
521 int top_pos = first.second->position() - first.second->ascent();
522 int bottom_pos = last.second->position() + last.second->descent();
523 bool first_visible = first.first == 0 && top_pos >= 0;
524 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
525 if (first_visible && last_visible) {
526 d->scrollbarParameters_.min = 0;
527 d->scrollbarParameters_.max = 0;
531 d->scrollbarParameters_.min = top_pos;
532 for (size_t i = 0; i != size_t(first.first); ++i)
533 d->scrollbarParameters_.min -= d->par_height_[i];
534 d->scrollbarParameters_.max = bottom_pos;
535 for (size_t i = last.first + 1; i != parsize; ++i)
536 d->scrollbarParameters_.max += d->par_height_[i];
538 d->scrollbarParameters_.position = 0;
539 // The reference is the top position so we remove one page.
540 if (lyxrc.scroll_below_document)
541 d->scrollbarParameters_.max -= minVisiblePart();
543 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
547 ScrollbarParameters const & BufferView::scrollbarParameters() const
549 return d->scrollbarParameters_;
553 docstring BufferView::toolTip(int x, int y) const
555 // Get inset under mouse, if there is one.
556 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
558 // No inset, no tooltip...
560 return covering_inset->toolTip(*this, x, y);
564 string BufferView::contextMenu(int x, int y) const
566 //If there is a selection, return the containing inset menu
567 if (d->cursor_.selection())
568 return d->cursor_.inset().contextMenu(*this, x, y);
570 // Get inset under mouse, if there is one.
571 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
573 return covering_inset->contextMenu(*this, x, y);
575 return buffer_.inset().contextMenu(*this, x, y);
579 void BufferView::scrollDocView(int value, bool update)
581 int const offset = value - d->scrollbarParameters_.position;
583 // No scrolling at all? No need to redraw anything
587 // If the offset is less than 2 screen height, prefer to scroll instead.
588 if (abs(offset) <= 2 * height_) {
589 d->anchor_ypos_ -= offset;
590 buffer_.changed(true);
591 updateHoveredInset();
595 // cut off at the top
596 if (value <= d->scrollbarParameters_.min) {
597 DocIterator dit = doc_iterator_begin(&buffer_);
598 showCursor(dit, false, update);
599 LYXERR(Debug::SCROLLING, "scroll to top");
603 // cut off at the bottom
604 if (value >= d->scrollbarParameters_.max) {
605 DocIterator dit = doc_iterator_end(&buffer_);
607 showCursor(dit, false, update);
608 LYXERR(Debug::SCROLLING, "scroll to bottom");
612 // find paragraph at target position
613 int par_pos = d->scrollbarParameters_.min;
615 for (; i != int(d->par_height_.size()); ++i) {
616 par_pos += d->par_height_[i];
617 if (par_pos >= value)
621 if (par_pos < value) {
622 // It seems we didn't find the correct pit so stay on the safe side and
624 LYXERR0("scrolling position not found!");
625 scrollDocView(d->scrollbarParameters_.max, update);
629 DocIterator dit = doc_iterator_begin(&buffer_);
631 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
632 showCursor(dit, false, update);
636 // FIXME: this method is not working well.
637 void BufferView::setCursorFromScrollbar()
639 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
641 int const height = 2 * defaultRowHeight();
642 int const first = height;
643 int const last = height_ - height;
645 Cursor const & oldcur = d->cursor_;
647 switch (cursorStatus(oldcur)) {
655 int const y = getPos(oldcur).y_;
656 newy = min(last, max(y, first));
660 // We reset the cursor because cursorStatus() does not
661 // work when the cursor is within mathed.
664 tm.setCursorFromCoordinates(cur, 0, newy);
666 // update the bufferview cursor and notify insets
667 // FIXME: Care about the d->cursor_ flags to redraw if needed
668 Cursor old = d->cursor_;
670 // the DEPM call in mouseSetCursor() might have destroyed the
671 // paragraph the cursor is in.
672 bool badcursor = old.fixIfBroken();
673 badcursor |= notifyCursorLeavesOrEnters(old, d->cursor_);
675 d->cursor_.fixIfBroken();
679 Change const BufferView::getCurrentChange() const
681 if (!d->cursor_.selection())
682 return Change(Change::UNCHANGED);
684 DocIterator dit = d->cursor_.selectionBegin();
685 return dit.paragraph().lookupChange(dit.pos());
689 // this could be used elsewhere as well?
690 // FIXME: This does not work within mathed!
691 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
693 Point const p = getPos(dit);
696 if (p.y_ > workHeight())
702 void BufferView::bookmarkEditPosition()
704 // Don't eat cpu time for each keystroke
705 if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
708 d->bookmark_edit_position_ = d->cursor_.paragraph().id();
712 void BufferView::saveBookmark(unsigned int idx)
714 // tentatively save bookmark, id and pos will be used to
715 // acturately locate a bookmark in a 'live' lyx session.
716 // pit and pos will be updated with bottom level pit/pos
718 if (!buffer_.isInternal()) {
719 theSession().bookmarks().save(
721 d->cursor_.bottom().pit(),
722 d->cursor_.bottom().pos(),
723 d->cursor_.paragraph().id(),
728 // emit message signal.
729 message(_("Save bookmark"));
734 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
735 int top_id, pos_type top_pos)
737 bool success = false;
740 d->cursor_.clearSelection();
742 // if a valid par_id is given, try it first
743 // This is the case for a 'live' bookmark when unique paragraph ID
744 // is used to track bookmarks.
746 dit = buffer_.getParFromID(top_id);
748 dit.pos() = min(dit.paragraph().size(), top_pos);
749 // Some slices of the iterator may not be
750 // reachable (e.g. closed collapsable inset)
751 // so the dociterator may need to be
752 // shortened. Otherwise, setCursor may crash
753 // lyx when the cursor can not be set to these
755 size_t const n = dit.depth();
756 for (size_t i = 0; i < n; ++i)
757 if (!dit[i].inset().editable()) {
765 // if top_id == 0, or searching through top_id failed
766 // This is the case for a 'restored' bookmark when only bottom
767 // (document level) pit was saved. Because of this, bookmark
768 // restoration is inaccurate. If a bookmark was within an inset,
769 // it will be restored to the left of the outmost inset that contains
771 if (bottom_pit < int(buffer_.paragraphs().size())) {
772 dit = doc_iterator_begin(&buffer_);
774 dit.pit() = bottom_pit;
775 dit.pos() = min(bottom_pos, dit.paragraph().size());
780 // Note: only bottom (document) level pit is set.
782 // set the current font.
783 d->cursor_.setCurrentFont();
784 // To center the screen on this new position we need the
785 // paragraph position which is computed at draw() time.
786 // So we need a redraw!
787 buffer_.changed(false);
796 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
798 if (lyxrc.rtl_support) {
799 if (d->cursor_.real_current_font.isRightToLeft()) {
800 if (d->intl_.keymap == Intl::PRIMARY)
801 d->intl_.keyMapSec();
803 if (d->intl_.keymap == Intl::SECONDARY)
804 d->intl_.keyMapPrim();
808 d->intl_.getTransManager().translateAndInsert(c, t, cur);
812 int BufferView::workWidth() const
818 void BufferView::recenter()
820 showCursor(d->cursor_, true, true);
824 void BufferView::showCursor()
826 showCursor(d->cursor_, false, true);
830 void BufferView::showCursor(DocIterator const & dit,
831 bool recenter, bool update)
833 if (scrollToCursor(dit, recenter) && update) {
834 buffer_.changed(true);
835 updateHoveredInset();
840 void BufferView::scrollToCursor()
842 if (scrollToCursor(d->cursor_, false)) {
843 buffer_.changed(true);
844 updateHoveredInset();
849 bool BufferView::scrollToCursor(DocIterator const & dit, bool recenter)
851 // We are not properly started yet, delay until resizing is
856 LYXERR(Debug::SCROLLING, "recentering!");
858 CursorSlice const & bot = dit.bottom();
859 TextMetrics & tm = d->text_metrics_[bot.text()];
861 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
862 int bot_pit = bot.pit();
863 if (bot_pit > max_pit) {
864 // FIXME: Why does this happen?
865 LYXERR0("bottom pit is greater that max pit: "
866 << bot_pit << " > " << max_pit);
870 if (bot_pit == tm.first().first - 1)
871 tm.newParMetricsUp();
872 else if (bot_pit == tm.last().first + 1)
873 tm.newParMetricsDown();
875 if (tm.contains(bot_pit)) {
876 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
877 LASSERT(!pm.rows().empty(), /**/);
878 // FIXME: smooth scrolling doesn't work in mathed.
879 CursorSlice const & cs = dit.innerTextSlice();
880 int offset = coordOffset(dit).y_;
881 int ypos = pm.position() + offset;
882 Dimension const & row_dim =
883 pm.getRow(cs.pos(), dit.boundary()).dimension();
886 scrolled = scroll(ypos - height_/2);
888 // We try to visualize the whole row, if the row height is larger than
889 // the screen height, we scroll to a heuristic value of height_ / 4.
890 // FIXME: This heuristic value should be replaced by a recursive search
891 // for a row in the inset that can be visualized completely.
892 else if (row_dim.height() > height_) {
893 if (ypos < defaultRowHeight())
894 scrolled = scroll(ypos - height_ / 4);
895 else if (ypos > height_ - defaultRowHeight())
896 scrolled = scroll(ypos - 3 * height_ / 4);
899 // If the top part of the row falls of the screen, we scroll
900 // up to align the top of the row with the top of the screen.
901 else if (ypos - row_dim.ascent() < 0 && ypos < height_) {
902 int ynew = row_dim.ascent();
903 scrolled = scrollUp(ynew - ypos);
906 // If the bottom of the row falls of the screen, we scroll down.
907 else if (ypos + row_dim.descent() > height_ && ypos > 0) {
908 int ynew = height_ - row_dim.descent();
909 scrolled = scrollDown(ypos - ynew);
912 // else, nothing to do, the cursor is already visible so we just return.
913 return scrolled != 0;
916 // fix inline completion position
917 if (d->inlineCompletionPos_.fixIfBroken())
918 d->inlineCompletionPos_ = DocIterator();
920 tm.redoParagraph(bot_pit);
921 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
922 int offset = coordOffset(dit).y_;
924 d->anchor_pit_ = bot_pit;
925 CursorSlice const & cs = dit.innerTextSlice();
926 Dimension const & row_dim =
927 pm.getRow(cs.pos(), dit.boundary()).dimension();
930 d->anchor_ypos_ = height_/2;
931 else if (d->anchor_pit_ == 0)
932 d->anchor_ypos_ = offset + pm.ascent();
933 else if (d->anchor_pit_ == max_pit)
934 d->anchor_ypos_ = height_ - offset - row_dim.descent();
935 else if (offset > height_)
936 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
938 d->anchor_ypos_ = defaultRowHeight() * 2;
944 void BufferView::makeDocumentClass()
946 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
947 buffer_.params().makeDocumentClass();
948 updateDocumentClass(olddc);
952 void BufferView::updateDocumentClass(DocumentClassConstPtr olddc)
954 message(_("Converting document to new document class..."));
956 StableDocIterator backcur(d->cursor_);
957 ErrorList & el = buffer_.errorList("Class Switch");
958 cap::switchBetweenClasses(
959 olddc, buffer_.params().documentClassPtr(),
960 static_cast<InsetText &>(buffer_.inset()), el);
962 setCursor(backcur.asDocIterator(&buffer_));
964 buffer_.errors("Class Switch");
968 /** Return the change status at cursor position, taking in account the
969 * status at each level of the document iterator (a table in a deleted
970 * footnote is deleted).
971 * When \param outer is true, the top slice is not looked at.
973 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
975 size_t const depth = dit.depth() - (outer ? 1 : 0);
977 for (size_t i = 0 ; i < depth ; ++i) {
978 CursorSlice const & slice = dit[i];
979 if (!slice.inset().inMathed()
980 && slice.pos() < slice.paragraph().size()) {
981 Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
982 if (ch != Change::UNCHANGED)
986 return Change::UNCHANGED;
990 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
992 FuncCode const act = cmd.action();
994 // Can we use a readonly buffer?
995 if (buffer_.isReadonly()
996 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
997 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
998 flag.message(from_utf8(N_("Document is read-only")));
999 flag.setEnabled(false);
1003 // Are we in a DELETED change-tracking region?
1004 if (lookupChangeType(d->cursor_, true) == Change::DELETED
1005 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1006 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1007 flag.message(from_utf8(N_("This portion of the document is deleted.")));
1008 flag.setEnabled(false);
1012 Cursor & cur = d->cursor_;
1014 if (cur.getStatus(cmd, flag))
1019 // FIXME: This is a bit problematic because we don't check if this is
1020 // a document BufferView or not for these LFUNs. We probably have to
1021 // dispatch both to currentBufferView() and, if that fails,
1022 // to documentBufferView(); same as we do now for current Buffer and
1023 // document Buffer. Ideally those LFUN should go to Buffer as they
1024 // operate on the full Buffer and the cursor is only needed either for
1025 // an Undo record or to restore a cursor position. But we don't know
1026 // how to do that inside Buffer of course.
1027 case LFUN_BUFFER_PARAMS_APPLY:
1028 case LFUN_LAYOUT_MODULES_CLEAR:
1029 case LFUN_LAYOUT_MODULE_ADD:
1030 case LFUN_LAYOUT_RELOAD:
1031 case LFUN_TEXTCLASS_APPLY:
1032 case LFUN_TEXTCLASS_LOAD:
1033 flag.setEnabled(!buffer_.isReadonly());
1037 // We do not use the LyXAction flag for readonly because Undo sets the
1038 // buffer clean/dirty status by itself.
1039 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasUndoStack());
1042 // We do not use the LyXAction flag for readonly because Redo sets the
1043 // buffer clean/dirty status by itself.
1044 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasRedoStack());
1046 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1047 case LFUN_FILE_INSERT_PLAINTEXT: {
1048 docstring const fname = cmd.argument();
1049 if (!FileName::isAbsolute(to_utf8(fname))) {
1050 flag.message(_("Absolute filename expected."));
1053 flag.setEnabled(cur.inTexted());
1056 case LFUN_FILE_INSERT:
1057 case LFUN_BOOKMARK_SAVE:
1058 // FIXME: Actually, these LFUNS should be moved to Text
1059 flag.setEnabled(cur.inTexted());
1062 case LFUN_FONT_STATE:
1063 case LFUN_LABEL_INSERT:
1064 case LFUN_INFO_INSERT:
1065 case LFUN_PARAGRAPH_GOTO:
1066 case LFUN_NOTE_NEXT:
1067 case LFUN_REFERENCE_NEXT:
1068 case LFUN_WORD_FIND:
1069 case LFUN_WORD_FIND_FORWARD:
1070 case LFUN_WORD_FIND_BACKWARD:
1071 case LFUN_WORD_REPLACE:
1074 case LFUN_MARK_TOGGLE:
1075 case LFUN_SCREEN_RECENTER:
1076 case LFUN_SCREEN_SHOW_CURSOR:
1077 case LFUN_BIBTEX_DATABASE_ADD:
1078 case LFUN_BIBTEX_DATABASE_DEL:
1079 case LFUN_STATISTICS:
1080 case LFUN_BRANCH_ADD_INSERT:
1081 case LFUN_KEYMAP_OFF:
1082 case LFUN_KEYMAP_PRIMARY:
1083 case LFUN_KEYMAP_SECONDARY:
1084 case LFUN_KEYMAP_TOGGLE:
1085 flag.setEnabled(true);
1088 case LFUN_WORD_FINDADV: {
1089 FindAndReplaceOptions opt;
1090 istringstream iss(to_utf8(cmd.argument()));
1092 flag.setEnabled(opt.repl_buf_name.empty()
1093 || !buffer_.isReadonly());
1096 case LFUN_LABEL_GOTO: {
1097 flag.setEnabled(!cmd.argument().empty()
1098 || getInsetByCode<InsetRef>(cur, REF_CODE));
1102 case LFUN_CHANGES_TRACK:
1103 flag.setEnabled(true);
1104 flag.setOnOff(buffer_.params().trackChanges);
1107 case LFUN_CHANGES_OUTPUT:
1108 flag.setEnabled(true);
1109 flag.setOnOff(buffer_.params().outputChanges);
1112 case LFUN_CHANGES_MERGE:
1113 case LFUN_CHANGE_NEXT:
1114 case LFUN_CHANGE_PREVIOUS:
1115 case LFUN_ALL_CHANGES_ACCEPT:
1116 case LFUN_ALL_CHANGES_REJECT:
1117 // TODO: context-sensitive enabling of LFUNs
1118 // In principle, these command should only be enabled if there
1119 // is a change in the document. However, without proper
1120 // optimizations, this will inevitably result in poor performance.
1121 flag.setEnabled(true);
1124 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
1125 flag.setOnOff(buffer_.params().compressed);
1129 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC: {
1130 flag.setOnOff(buffer_.params().output_sync);
1134 case LFUN_SCREEN_UP:
1135 case LFUN_SCREEN_DOWN:
1137 case LFUN_SCREEN_UP_SELECT:
1138 case LFUN_SCREEN_DOWN_SELECT:
1139 case LFUN_INSET_FORALL:
1140 flag.setEnabled(true);
1143 case LFUN_LAYOUT_TABULAR:
1144 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1148 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1151 case LFUN_LAYOUT_PARAGRAPH:
1152 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1155 case LFUN_DIALOG_SHOW_NEW_INSET:
1156 // FIXME: this is wrong, but I do not understand the
1158 if (cur.inset().lyxCode() == CAPTION_CODE)
1159 return cur.inset().getStatus(cur, cmd, flag);
1160 // FIXME we should consider passthru paragraphs too.
1161 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1164 case LFUN_CITATION_INSERT: {
1165 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1166 // FIXME: This could turn in a recursive hell.
1167 // Shouldn't we use Buffer::getStatus() instead?
1168 flag.setEnabled(lyx::getStatus(fr).enabled());
1171 case LFUN_INSET_APPLY: {
1172 string const name = cmd.getArg(0);
1173 Inset * inset = editedInset(name);
1175 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1176 if (!inset->getStatus(cur, fr, flag)) {
1177 // Every inset is supposed to handle this
1178 LASSERT(false, break);
1181 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1182 flag = lyx::getStatus(fr);
1187 // FIXME We do not really want this here, but at present we need to
1188 // handle their dispatch here, for reasons explained there, so we'll
1189 // handle this here, too, for consistency.
1190 case LFUN_BRANCH_ACTIVATE:
1191 case LFUN_BRANCH_DEACTIVATE:
1192 case LFUN_BRANCH_MASTER_ACTIVATE:
1193 case LFUN_BRANCH_MASTER_DEACTIVATE: {
1194 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
1195 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
1196 BranchList const & branchList = master ? buffer().masterBuffer()->params().branchlist()
1197 : buffer().params().branchlist();
1198 docstring const branchName = cmd.argument();
1199 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
1211 Inset * BufferView::editedInset(string const & name) const
1213 map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1214 return it == d->edited_insets_.end() ? 0 : it->second;
1218 void BufferView::editInset(string const & name, Inset * inset)
1220 d->edited_insets_[name] = inset;
1224 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1226 LYXERR(Debug::ACTION, "BufferView::dispatch: cmd: " << cmd);
1228 string const argument = to_utf8(cmd.argument());
1229 Cursor & cur = d->cursor_;
1231 // Don't dispatch function that does not apply to internal buffers.
1232 if (buffer_.isInternal()
1233 && lyxaction.funcHasFlag(cmd.action(), LyXAction::NoInternal))
1236 // We'll set this back to false if need be.
1237 bool dispatched = true;
1238 buffer_.undo().beginUndoGroup();
1240 FuncCode const act = cmd.action();
1243 case LFUN_BUFFER_PARAMS_APPLY: {
1244 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
1245 cur.recordUndoFullDocument();
1246 istringstream ss(to_utf8(cmd.argument()));
1249 int const unknown_tokens = buffer_.readHeader(lex);
1250 if (unknown_tokens != 0) {
1251 LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1252 << unknown_tokens << " unknown token"
1253 << (unknown_tokens == 1 ? "" : "s"));
1255 updateDocumentClass(olddc);
1257 // We are most certainly here because of a change in the document
1258 // It is then better to make sure that all dialogs are in sync with
1259 // current document settings.
1260 dr.screenUpdate(Update::Force | Update::FitCursor);
1261 dr.forceBufferUpdate();
1265 case LFUN_LAYOUT_MODULES_CLEAR: {
1266 cur.recordUndoFullDocument();
1267 buffer_.params().clearLayoutModules();
1268 makeDocumentClass();
1269 dr.screenUpdate(Update::Force);
1270 dr.forceBufferUpdate();
1274 case LFUN_LAYOUT_MODULE_ADD: {
1275 BufferParams const & params = buffer_.params();
1276 if (!params.moduleCanBeAdded(argument)) {
1277 LYXERR0("Module `" << argument <<
1278 "' cannot be added due to failed requirements or "
1279 "conflicts with installed modules.");
1282 cur.recordUndoFullDocument();
1283 buffer_.params().addLayoutModule(argument);
1284 makeDocumentClass();
1285 dr.screenUpdate(Update::Force);
1286 dr.forceBufferUpdate();
1290 case LFUN_TEXTCLASS_APPLY: {
1291 // since this shortcircuits, the second call is made only if
1293 bool const success =
1294 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1295 LayoutFileList::get().load(argument, buffer_.filePath());
1297 docstring s = bformat(_("The document class `%1$s' "
1298 "could not be loaded."), from_utf8(argument));
1299 frontend::Alert::error(_("Could not load class"), s);
1303 LayoutFile const * old_layout = buffer_.params().baseClass();
1304 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1306 if (old_layout == new_layout)
1310 // Save the old, possibly modular, layout for use in conversion.
1311 cur.recordUndoFullDocument();
1312 buffer_.params().setBaseClass(argument);
1313 makeDocumentClass();
1314 dr.screenUpdate(Update::Force);
1315 dr.forceBufferUpdate();
1319 case LFUN_TEXTCLASS_LOAD: {
1320 // since this shortcircuits, the second call is made only if
1322 bool const success =
1323 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1324 LayoutFileList::get().load(argument, buffer_.filePath());
1326 docstring s = bformat(_("The document class `%1$s' "
1327 "could not be loaded."), from_utf8(argument));
1328 frontend::Alert::error(_("Could not load class"), s);
1333 case LFUN_LAYOUT_RELOAD: {
1334 LayoutFileIndex bc = buffer_.params().baseClassID();
1335 LayoutFileList::get().reset(bc);
1336 buffer_.params().setBaseClass(bc);
1337 makeDocumentClass();
1338 dr.screenUpdate(Update::Force);
1339 dr.forceBufferUpdate();
1344 dr.setMessage(_("Undo"));
1345 cur.clearSelection();
1346 if (!cur.textUndo())
1347 dr.setMessage(_("No further undo information"));
1349 dr.screenUpdate(Update::Force | Update::FitCursor);
1350 dr.forceBufferUpdate();
1354 dr.setMessage(_("Redo"));
1355 cur.clearSelection();
1356 if (!cur.textRedo())
1357 dr.setMessage(_("No further redo information"));
1359 dr.screenUpdate(Update::Force | Update::FitCursor);
1360 dr.forceBufferUpdate();
1363 case LFUN_FONT_STATE:
1364 dr.setMessage(cur.currentState());
1367 case LFUN_BOOKMARK_SAVE:
1368 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1371 case LFUN_LABEL_GOTO: {
1372 docstring label = cmd.argument();
1373 if (label.empty()) {
1375 getInsetByCode<InsetRef>(cur, REF_CODE);
1377 label = inset->getParam("reference");
1378 // persistent=false: use temp_bookmark
1382 if (!label.empty()) {
1384 // at the moment, this is redundant, since gotoLabel will
1385 // eventually call LFUN_PARAGRAPH_GOTO, but it seems best
1387 dr.screenUpdate(Update::Force | Update::FitCursor);
1392 case LFUN_PARAGRAPH_GOTO: {
1393 int const id = convert<int>(cmd.getArg(0));
1394 int const pos = convert<int>(cmd.getArg(1));
1396 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1397 b = theBufferList().next(b)) {
1399 DocIterator dit = b->getParFromID(id);
1401 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1405 LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1406 << " found in buffer `"
1407 << b->absFileName() << "'.");
1409 if (b == &buffer_) {
1413 dr.screenUpdate(Update::Force | Update::FitCursor);
1415 // Switch to other buffer view and resend cmd
1416 lyx::dispatch(FuncRequest(
1417 LFUN_BUFFER_SWITCH, b->absFileName()));
1425 case LFUN_NOTE_NEXT:
1426 gotoInset(this, NOTE_CODE, false);
1429 case LFUN_REFERENCE_NEXT: {
1430 vector<InsetCode> tmp;
1431 tmp.push_back(LABEL_CODE);
1432 tmp.push_back(REF_CODE);
1433 gotoInset(this, tmp, true);
1437 case LFUN_CHANGES_TRACK:
1438 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1441 case LFUN_CHANGES_OUTPUT:
1442 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1443 if (buffer_.params().outputChanges) {
1444 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1445 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1446 LaTeXFeatures::isAvailable("xcolor");
1448 if (!dvipost && !xcolorulem) {
1449 Alert::warning(_("Changes not shown in LaTeX output"),
1450 _("Changes will not be highlighted in LaTeX output, "
1451 "because neither dvipost nor xcolor/ulem are installed.\n"
1452 "Please install these packages or redefine "
1453 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1454 } else if (!xcolorulem) {
1455 Alert::warning(_("Changes not shown in LaTeX output"),
1456 _("Changes will not be highlighted in LaTeX output "
1457 "when using pdflatex, because xcolor and ulem are not installed.\n"
1458 "Please install both packages or redefine "
1459 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1464 case LFUN_CHANGE_NEXT:
1465 findNextChange(this);
1466 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1467 dr.screenUpdate(Update::Force | Update::FitCursor);
1470 case LFUN_CHANGE_PREVIOUS:
1471 findPreviousChange(this);
1472 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1473 dr.screenUpdate(Update::Force | Update::FitCursor);
1476 case LFUN_CHANGES_MERGE:
1477 if (findNextChange(this) || findPreviousChange(this)) {
1478 dr.screenUpdate(Update::Force | Update::FitCursor);
1479 dr.forceBufferUpdate();
1480 showDialog("changes");
1484 case LFUN_ALL_CHANGES_ACCEPT:
1485 // select complete document
1487 cur.selHandle(true);
1488 buffer_.text().cursorBottom(cur);
1489 // accept everything in a single step to support atomic undo
1490 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
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_ALL_CHANGES_REJECT:
1498 // select complete document
1500 cur.selHandle(true);
1501 buffer_.text().cursorBottom(cur);
1502 // reject everything in a single step to support atomic undo
1503 // Note: reject does not work recursively; the user may have to repeat the operation
1504 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1506 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1507 dr.screenUpdate(Update::Force | Update::FitCursor);
1508 dr.forceBufferUpdate();
1511 case LFUN_WORD_FIND_FORWARD:
1512 case LFUN_WORD_FIND_BACKWARD: {
1513 static docstring last_search;
1514 docstring searched_string;
1516 if (!cmd.argument().empty()) {
1517 last_search = cmd.argument();
1518 searched_string = cmd.argument();
1520 searched_string = last_search;
1523 if (searched_string.empty())
1526 bool const fw = act == LFUN_WORD_FIND_FORWARD;
1527 docstring const data =
1528 find2string(searched_string, true, false, fw);
1529 bool found = lyxfind(this, FuncRequest(LFUN_WORD_FIND, data));
1531 dr.screenUpdate(Update::Force | Update::FitCursor);
1535 case LFUN_WORD_FIND: {
1536 FuncRequest req = cmd;
1537 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1538 req = d->search_request_cache_;
1539 if (req.argument().empty()) {
1540 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1543 if (lyxfind(this, req))
1544 dr.screenUpdate(Update::Force | Update::FitCursor);
1546 message(_("String not found!"));
1547 d->search_request_cache_ = req;
1551 case LFUN_WORD_REPLACE: {
1552 bool has_deleted = false;
1553 if (cur.selection()) {
1554 DocIterator beg = cur.selectionBegin();
1555 DocIterator end = cur.selectionEnd();
1556 if (beg.pit() == end.pit()) {
1557 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1558 if (!cur.inMathed() && cur.paragraph().isDeleted(p)) {
1565 if (lyxreplace(this, cmd, has_deleted)) {
1566 dr.forceBufferUpdate();
1567 dr.screenUpdate(Update::Force | Update::FitCursor);
1572 case LFUN_WORD_FINDADV: {
1573 FindAndReplaceOptions opt;
1574 istringstream iss(to_utf8(cmd.argument()));
1576 if (findAdv(this, opt)) {
1577 dr.screenUpdate(Update::Force | Update::FitCursor);
1588 cur.clearSelection();
1589 dr.setMessage(from_utf8(N_("Mark off")));
1593 cur.clearSelection();
1595 dr.setMessage(from_utf8(N_("Mark on")));
1598 case LFUN_MARK_TOGGLE:
1599 cur.setSelection(false);
1602 dr.setMessage(from_utf8(N_("Mark removed")));
1605 dr.setMessage(from_utf8(N_("Mark set")));
1610 case LFUN_SCREEN_SHOW_CURSOR:
1614 case LFUN_SCREEN_RECENTER:
1618 case LFUN_BIBTEX_DATABASE_ADD: {
1619 Cursor tmpcur = cur;
1620 findInset(tmpcur, BIBTEX_CODE, false);
1621 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1624 if (inset->addDatabase(cmd.argument())) {
1625 buffer_.invalidateBibfileCache();
1626 dr.forceBufferUpdate();
1632 case LFUN_BIBTEX_DATABASE_DEL: {
1633 Cursor tmpcur = cur;
1634 findInset(tmpcur, BIBTEX_CODE, false);
1635 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1638 if (inset->delDatabase(cmd.argument())) {
1639 buffer_.invalidateBibfileCache();
1640 dr.forceBufferUpdate();
1646 case LFUN_STATISTICS: {
1647 DocIterator from, to;
1648 if (cur.selection()) {
1649 from = cur.selectionBegin();
1650 to = cur.selectionEnd();
1652 from = doc_iterator_begin(&buffer_);
1653 to = doc_iterator_end(&buffer_);
1655 buffer_.updateStatistics(from, to);
1656 int const words = buffer_.wordCount();
1657 int const chars = buffer_.charCount(false);
1658 int const chars_blanks = buffer_.charCount(true);
1660 if (cur.selection())
1661 message = _("Statistics for the selection:");
1663 message = _("Statistics for the document:");
1666 message += bformat(_("%1$d words"), words);
1668 message += _("One word");
1670 if (chars_blanks != 1)
1671 message += bformat(_("%1$d characters (including blanks)"),
1674 message += _("One character (including blanks)");
1677 message += bformat(_("%1$d characters (excluding blanks)"),
1680 message += _("One character (excluding blanks)");
1682 Alert::information(_("Statistics"), message);
1686 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1687 // turn compression on/off
1688 buffer_.params().compressed = !buffer_.params().compressed;
1691 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
1692 buffer_.params().output_sync = !buffer_.params().output_sync;
1695 case LFUN_SCREEN_UP:
1696 case LFUN_SCREEN_DOWN: {
1697 Point p = getPos(cur);
1698 // This code has been commented out to enable to scroll down a
1699 // document, even if there are large insets in it (see bug #5465).
1700 /*if (p.y_ < 0 || p.y_ > height_) {
1701 // The cursor is off-screen so recenter before proceeding.
1705 int const scrolled = scroll(act == LFUN_SCREEN_UP
1706 ? -height_ : height_);
1707 if (act == LFUN_SCREEN_UP && scrolled > -height_)
1709 if (act == LFUN_SCREEN_DOWN && scrolled < height_)
1710 p = Point(width_, height_);
1712 bool const in_texted = cur.inTexted();
1713 cur.setCursor(doc_iterator_begin(cur.buffer()));
1714 cur.selHandle(false);
1715 buffer_.changed(true);
1716 updateHoveredInset();
1718 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1719 true, act == LFUN_SCREEN_UP);
1720 //FIXME: what to do with cur.x_target()?
1721 bool update = in_texted && cur.bv().checkDepm(cur, old);
1724 if (update || cur.mark())
1725 dr.screenUpdate(Update::Force | Update::FitCursor);
1727 dr.forceBufferUpdate();
1732 string const scroll_type = cmd.getArg(0);
1733 int scroll_step = 0;
1734 if (scroll_type == "line")
1735 scroll_step = d->scrollbarParameters_.single_step;
1736 else if (scroll_type == "page")
1737 scroll_step = d->scrollbarParameters_.page_step;
1740 string const scroll_quantity = cmd.getArg(1);
1741 if (scroll_quantity == "up")
1742 scrollUp(scroll_step);
1743 else if (scroll_quantity == "down")
1744 scrollDown(scroll_step);
1746 int const scroll_value = convert<int>(scroll_quantity);
1748 scroll(scroll_step * scroll_value);
1750 buffer_.changed(true);
1751 updateHoveredInset();
1752 dr.forceBufferUpdate();
1756 case LFUN_SCREEN_UP_SELECT: {
1757 // FIXME: why is the algorithm different from LFUN_SCREEN_UP?
1758 cur.selHandle(true);
1759 if (isTopScreen()) {
1760 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1764 int y = getPos(cur).y_;
1765 int const ymin = y - height_ + defaultRowHeight();
1766 while (y > ymin && cur.up())
1770 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1774 case LFUN_SCREEN_DOWN_SELECT: {
1775 // FIXME: why is the algorithm different from LFUN_SCREEN_DOWN?
1776 cur.selHandle(true);
1777 if (isBottomScreen()) {
1778 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1782 int y = getPos(cur).y_;
1783 int const ymax = y + height_ - defaultRowHeight();
1784 while (y < ymax && cur.down())
1788 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1793 // This would be in Buffer class if only Cursor did not
1794 // require a bufferview
1795 case LFUN_INSET_FORALL: {
1796 docstring const name = from_utf8(cmd.getArg(0));
1797 string const commandstr = cmd.getLongArg(1);
1798 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
1800 // an arbitrary number to limit number of iterations
1801 const int max_iter = 100000;
1803 Cursor & cur = d->cursor_;
1804 Cursor const savecur = cur;
1806 if (!cur.nextInset())
1808 cur.beginUndoGroup();
1809 while(cur && iterations < max_iter) {
1810 Inset * ins = cur.nextInset();
1813 docstring insname = ins->layoutName();
1814 while (!insname.empty()) {
1815 if (insname == name || name == from_utf8("*")) {
1817 lyx::dispatch(fr, dr);
1821 size_t const i = insname.rfind(':');
1822 if (i == string::npos)
1824 insname = insname.substr(0, i);
1831 dr.screenUpdate(Update::Force);
1832 dr.forceBufferUpdate();
1834 if (iterations >= max_iter) {
1836 dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
1838 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
1843 case LFUN_BRANCH_ADD_INSERT: {
1844 docstring branch_name = from_utf8(cmd.getArg(0));
1845 if (branch_name.empty())
1846 if (!Alert::askForText(branch_name, _("Branch name")) ||
1847 branch_name.empty())
1850 DispatchResult drtmp;
1851 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
1852 if (drtmp.error()) {
1853 Alert::warning(_("Branch already exists"), drtmp.message());
1856 BranchList & branch_list = buffer_.params().branchlist();
1857 vector<docstring> const branches =
1858 getVectorFromString(branch_name, branch_list.separator());
1859 for (vector<docstring>::const_iterator it = branches.begin();
1860 it != branches.end(); ++it) {
1862 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch_name));
1867 case LFUN_KEYMAP_OFF:
1868 getIntl().keyMapOn(false);
1871 case LFUN_KEYMAP_PRIMARY:
1872 getIntl().keyMapPrim();
1875 case LFUN_KEYMAP_SECONDARY:
1876 getIntl().keyMapSec();
1879 case LFUN_KEYMAP_TOGGLE:
1880 getIntl().toggleKeyMap();
1883 case LFUN_DIALOG_SHOW_NEW_INSET: {
1884 string const name = cmd.getArg(0);
1885 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1886 if (decodeInsetParam(name, data, buffer_))
1887 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1889 lyxerr << "Inset type '" << name <<
1890 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
1894 case LFUN_CITATION_INSERT: {
1895 if (argument.empty()) {
1896 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1899 // we can have one optional argument, delimited by '|'
1900 // citation-insert <key>|<text_before>
1901 // this should be enhanced to also support text_after
1902 // and citation style
1903 string arg = argument;
1905 if (contains(argument, "|")) {
1906 arg = token(argument, '|', 0);
1907 opt1 = token(argument, '|', 1);
1909 InsetCommandParams icp(CITE_CODE);
1910 icp["key"] = from_utf8(arg);
1912 icp["before"] = from_utf8(opt1);
1913 string icstr = InsetCommand::params2string(icp);
1914 FuncRequest fr(LFUN_INSET_INSERT, icstr);
1919 case LFUN_INSET_APPLY: {
1920 string const name = cmd.getArg(0);
1921 Inset * inset = editedInset(name);
1923 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1927 // put cursor in front of inset.
1928 if (!setCursorFromInset(inset)) {
1929 LASSERT(false, break);
1932 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1933 inset->dispatch(cur, fr);
1934 dr.screenUpdate(cur.result().screenUpdate());
1935 if (cur.result().needBufferUpdate())
1936 dr.forceBufferUpdate();
1941 // The change of language of buffer belongs to the Buffer class.
1942 // We have to do it here because we need a cursor for Undo.
1943 // When Undo::recordUndoBufferParams() is implemented someday
1944 // LFUN_BUFFER_LANGUAGE should be handled by the Buffer class.
1945 case LFUN_BUFFER_LANGUAGE: {
1946 Language const * oldL = buffer_.params().language;
1947 Language const * newL = languages.getLanguage(argument);
1948 if (!newL || oldL == newL)
1950 if (oldL->rightToLeft() == newL->rightToLeft()) {
1951 cur.recordUndoFullDocument();
1952 buffer_.changeLanguage(oldL, newL);
1953 cur.setCurrentFont();
1954 dr.forceBufferUpdate();
1959 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1960 case LFUN_FILE_INSERT_PLAINTEXT: {
1961 bool const as_paragraph = (act == LFUN_FILE_INSERT_PLAINTEXT_PARA);
1962 string const fname = to_utf8(cmd.argument());
1963 if (!FileName::isAbsolute(fname))
1964 dr.setMessage(_("Absolute filename expected."));
1966 insertPlaintextFile(FileName(fname), as_paragraph);
1970 // FIXME We do not really want this here, but it has to be at present
1971 // because we need a cursor for the recordUndoFullDocument call. What
1972 // we would really like is a recordUndoBufferParams call that did not
1973 // need a cursor, but we do not have that yet.
1974 // So, if this does get fixed, this code can be moved back to Buffer.cpp,
1975 // and the corresponding code in getStatus() should be moved back, too.
1976 case LFUN_BRANCH_ACTIVATE:
1977 case LFUN_BRANCH_DEACTIVATE:
1978 case LFUN_BRANCH_MASTER_ACTIVATE:
1979 case LFUN_BRANCH_MASTER_DEACTIVATE: {
1980 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
1981 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
1982 Buffer * buf = master ? const_cast<Buffer *>(buffer().masterBuffer())
1985 docstring const branch_name = cmd.argument();
1986 // the case without a branch name is handled elsewhere
1987 if (branch_name.empty()) {
1991 Branch * branch = buf->params().branchlist().find(branch_name);
1993 LYXERR0("Branch " << branch_name << " does not exist.");
1995 docstring const msg =
1996 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2000 bool activate = (cmd.action() == LFUN_BRANCH_ACTIVATE
2001 || cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2002 if (branch->isSelected() != activate) {
2003 branch->setSelected(activate);
2004 cur.recordUndoFullDocument();
2006 dr.screenUpdate(Update::Force);
2007 dr.forceBufferUpdate();
2013 // OK, so try the Buffer itself...
2014 buffer_.dispatch(cmd, dr);
2015 dispatched = dr.dispatched();
2019 buffer_.undo().endUndoGroup();
2020 dr.dispatched(dispatched);
2024 docstring const BufferView::requestSelection()
2026 Cursor & cur = d->cursor_;
2028 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
2029 if (!cur.selection()) {
2030 d->xsel_cache_.set = false;
2034 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
2035 if (!d->xsel_cache_.set ||
2036 cur.top() != d->xsel_cache_.cursor ||
2037 cur.realAnchor().top() != d->xsel_cache_.anchor)
2039 d->xsel_cache_.cursor = cur.top();
2040 d->xsel_cache_.anchor = cur.realAnchor().top();
2041 d->xsel_cache_.set = cur.selection();
2042 return cur.selectionAsString(false);
2048 void BufferView::clearSelection()
2050 d->cursor_.clearSelection();
2051 // Clear the selection buffer. Otherwise a subsequent
2052 // middle-mouse-button paste would use the selection buffer,
2053 // not the more current external selection.
2054 cap::clearSelection();
2055 d->xsel_cache_.set = false;
2056 // The buffer did not really change, but this causes the
2057 // redraw we need because we cleared the selection above.
2058 buffer_.changed(false);
2062 void BufferView::resize(int width, int height)
2064 // Update from work area
2068 // Clear the paragraph height cache.
2069 d->par_height_.clear();
2070 // Redo the metrics.
2075 Inset const * BufferView::getCoveringInset(Text const & text,
2078 TextMetrics & tm = d->text_metrics_[&text];
2079 Inset * inset = tm.checkInsetHit(x, y);
2083 if (!inset->descendable(*this))
2084 // No need to go further down if the inset is not
2088 size_t cell_number = inset->nargs();
2089 // Check all the inner cell.
2090 for (size_t i = 0; i != cell_number; ++i) {
2091 Text const * inner_text = inset->getText(i);
2094 Inset const * inset_deeper =
2095 getCoveringInset(*inner_text, x, y);
2097 return inset_deeper;
2105 void BufferView::updateHoveredInset() const
2107 // Get inset under mouse, if there is one.
2108 int const x = d->mouse_position_cache_.x_;
2109 int const y = d->mouse_position_cache_.y_;
2110 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
2112 d->clickable_inset_ = covering_inset && covering_inset->clickable(x, y);
2114 if (covering_inset == d->last_inset_)
2115 // Same inset, no need to do anything...
2118 bool need_redraw = false;
2119 if (d->last_inset_) {
2120 // Remove the hint on the last hovered inset (if any).
2121 need_redraw |= d->last_inset_->setMouseHover(this, false);
2125 if (covering_inset && covering_inset->setMouseHover(this, true)) {
2127 // Only the insets that accept the hover state, do
2128 // clear the last_inset_, so only set the last_inset_
2129 // member if the hovered setting is accepted.
2130 d->last_inset_ = covering_inset;
2134 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
2135 << d->mouse_position_cache_.x_ << ", "
2136 << d->mouse_position_cache_.y_ << ")");
2138 d->update_strategy_ = DecorationUpdate;
2140 // This event (moving without mouse click) is not passed further.
2141 // This should be changed if it is further utilized.
2142 buffer_.changed(false);
2147 void BufferView::clearLastInset(Inset * inset) const
2149 if (d->last_inset_ != inset) {
2150 LYXERR0("Wrong last_inset!");
2151 LASSERT(false, /**/);
2157 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
2159 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
2161 // This is only called for mouse related events including
2162 // LFUN_FILE_OPEN generated by drag-and-drop.
2163 FuncRequest cmd = cmd0;
2165 Cursor old = cursor();
2167 cur.push(buffer_.inset());
2168 cur.setSelection(d->cursor_.selection());
2170 // Either the inset under the cursor or the
2171 // surrounding Text will handle this event.
2173 // make sure we stay within the screen...
2174 cmd.set_y(min(max(cmd.y(), -1), height_));
2176 d->mouse_position_cache_.x_ = cmd.x();
2177 d->mouse_position_cache_.y_ = cmd.y();
2179 if (cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
2180 updateHoveredInset();
2184 // Build temporary cursor.
2185 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x(), cmd.y());
2187 // Put anchor at the same position.
2190 cur.beginUndoGroup();
2192 // Try to dispatch to an non-editable inset near this position
2193 // via the temp cursor. If the inset wishes to change the real
2194 // cursor it has to do so explicitly by using
2195 // cur.bv().cursor() = cur; (or similar)
2197 inset->dispatch(cur, cmd);
2199 // Now dispatch to the temporary cursor. If the real cursor should
2200 // be modified, the inset's dispatch has to do so explicitly.
2201 if (!inset || !cur.result().dispatched())
2206 // Notify left insets
2208 bool badcursor = old.fixIfBroken() | cur.fixIfBroken();
2209 badcursor |= notifyCursorLeavesOrEnters(old, cur);
2211 cursor().fixIfBroken();
2214 // Do we have a selection?
2215 theSelection().haveSelection(cursor().selection());
2217 if (cur.needBufferUpdate()) {
2218 cur.clearBufferUpdate();
2219 buffer().updateBuffer();
2222 // If the command has been dispatched,
2223 if (cur.result().dispatched() || cur.result().screenUpdate())
2224 processUpdateFlags(cur.result().screenUpdate());
2228 int BufferView::minVisiblePart()
2230 return 2 * defaultRowHeight();
2234 int BufferView::scroll(int y)
2237 return scrollDown(y);
2239 return scrollUp(-y);
2244 int BufferView::scrollDown(int offset)
2246 Text * text = &buffer_.text();
2247 TextMetrics & tm = d->text_metrics_[text];
2248 int const ymax = height_ + offset;
2250 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2251 int bottom_pos = last.second->position() + last.second->descent();
2252 if (lyxrc.scroll_below_document)
2253 bottom_pos += height_ - minVisiblePart();
2254 if (last.first + 1 == int(text->paragraphs().size())) {
2255 if (bottom_pos <= height_)
2257 offset = min(offset, bottom_pos - height_);
2260 if (bottom_pos > ymax)
2262 tm.newParMetricsDown();
2264 d->anchor_ypos_ -= offset;
2269 int BufferView::scrollUp(int offset)
2271 Text * text = &buffer_.text();
2272 TextMetrics & tm = d->text_metrics_[text];
2273 int ymin = - offset;
2275 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2276 int top_pos = first.second->position() - first.second->ascent();
2277 if (first.first == 0) {
2280 offset = min(offset, - top_pos);
2285 tm.newParMetricsUp();
2287 d->anchor_ypos_ += offset;
2292 void BufferView::setCursorFromRow(int row)
2296 pit_type newpit = 0;
2297 pos_type newpos = 0;
2299 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
2301 bool posvalid = (tmpid != -1);
2303 // we need to make sure that the row and position
2304 // we got back are valid, because the buffer may well
2305 // have changed since we last generated the LaTeX.
2306 DocIterator const dit = buffer_.getParFromID(tmpid);
2307 if (dit == doc_iterator_end(&buffer_))
2311 // now have to check pos.
2313 Paragraph const & par = buffer_.text().getPar(newpit);
2314 if (newpos > par.size()) {
2315 LYXERR0("Requested position no longer valid.");
2316 newpos = par.size() - 1;
2321 frontend::Alert::error(_("Inverse Search Failed"),
2322 _("Invalid position requested by inverse search.\n"
2323 "You need to update the viewed document."));
2327 buffer_.text().setCursor(d->cursor_, newpit, newpos);
2328 d->cursor_.setSelection(false);
2329 d->cursor_.resetAnchor();
2334 bool BufferView::setCursorFromInset(Inset const * inset)
2336 // are we already there?
2337 if (cursor().nextInset() == inset)
2340 // Inset is not at cursor position. Find it in the document.
2343 while (cur && cur.nextInset() != inset)
2354 void BufferView::gotoLabel(docstring const & label)
2356 ListOfBuffers bufs = buffer().allRelatives();
2357 ListOfBuffers::iterator it = bufs.begin();
2358 for (; it != bufs.end(); ++it) {
2359 Buffer const * buf = *it;
2362 Toc & toc = buf->tocBackend().toc("label");
2363 TocIterator toc_it = toc.begin();
2364 TocIterator end = toc.end();
2365 for (; toc_it != end; ++toc_it) {
2366 if (label == toc_it->str()) {
2367 lyx::dispatch(toc_it->action());
2375 TextMetrics const & BufferView::textMetrics(Text const * t) const
2377 return const_cast<BufferView *>(this)->textMetrics(t);
2381 TextMetrics & BufferView::textMetrics(Text const * t)
2384 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
2385 if (tmc_it == d->text_metrics_.end()) {
2386 tmc_it = d->text_metrics_.insert(
2387 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
2389 return tmc_it->second;
2393 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2396 return textMetrics(t).parMetrics(pit);
2400 int BufferView::workHeight() const
2406 void BufferView::setCursor(DocIterator const & dit)
2409 size_t const n = dit.depth();
2410 for (size_t i = 0; i < n; ++i)
2411 dit[i].inset().edit(d->cursor_, true);
2413 d->cursor_.setCursor(dit);
2414 d->cursor_.setSelection(false);
2416 // It seems on general grounds as if this is probably needed, but
2417 // it is not yet clear.
2418 // See bug #7394 and r38388.
2419 // d->cursor.resetAnchor();
2423 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2425 // Would be wrong to delete anything if we have a selection.
2426 if (cur.selection())
2429 bool need_anchor_change = false;
2430 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
2431 need_anchor_change);
2433 if (need_anchor_change)
2441 cur.forceBufferUpdate();
2442 cur.screenUpdateFlags(Update::Force);
2447 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
2449 LASSERT(&cur.bv() == this, /**/);
2452 // this event will clear selection so we save selection for
2453 // persistent selection
2454 cap::saveSelection(cursor());
2456 d->cursor_.macroModeClose();
2457 // If a macro has been finalized, the cursor might have been broken
2460 // Has the cursor just left the inset?
2461 bool const leftinset = (&d->cursor_.inset() != &cur.inset());
2463 d->cursor_.fixIfBroken();
2465 // FIXME: shift-mouse selection doesn't work well across insets.
2466 bool const do_selection =
2467 select && &d->cursor_.normalAnchor().inset() == &cur.inset();
2469 // do the dEPM magic if needed
2470 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2471 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2472 // the leftinset bool would not be necessary (badcursor instead).
2473 bool update = leftinset;
2474 if (!do_selection && d->cursor_.inTexted())
2475 update |= checkDepm(cur, d->cursor_);
2478 d->cursor_.resetAnchor();
2479 d->cursor_.setCursor(cur);
2480 d->cursor_.boundary(cur.boundary());
2482 d->cursor_.setSelection();
2484 d->cursor_.clearSelection();
2486 d->cursor_.finishUndo();
2487 d->cursor_.setCurrentFont();
2489 cur.forceBufferUpdate();
2494 void BufferView::putSelectionAt(DocIterator const & cur,
2495 int length, bool backwards)
2497 d->cursor_.clearSelection();
2503 d->cursor_.pos() += length;
2504 d->cursor_.setSelection(d->cursor_, -length);
2506 d->cursor_.setSelection(d->cursor_, length);
2511 bool BufferView::selectIfEmpty(DocIterator & cur)
2513 if (!cur.paragraph().empty())
2516 pit_type const beg_pit = cur.pit();
2518 // The paragraph associated to this item isn't
2519 // the first one, so it can be selected
2522 // We have to resort to select the space between the
2523 // end of this item and the begin of the next one
2527 // If it is the only item in the document,
2528 // nothing can be selected
2531 pit_type const end_pit = cur.pit();
2532 pos_type const end_pos = cur.pos();
2533 d->cursor_.clearSelection();
2535 d->cursor_.setCursor(cur);
2536 d->cursor_.pit() = beg_pit;
2537 d->cursor_.pos() = 0;
2538 d->cursor_.setSelection(false);
2539 d->cursor_.resetAnchor();
2540 d->cursor_.pit() = end_pit;
2541 d->cursor_.pos() = end_pos;
2542 d->cursor_.setSelection();
2547 Cursor & BufferView::cursor()
2553 Cursor const & BufferView::cursor() const
2559 pit_type BufferView::anchor_ref() const
2561 return d->anchor_pit_;
2565 bool BufferView::singleParUpdate()
2567 Text & buftext = buffer_.text();
2568 pit_type const bottom_pit = d->cursor_.bottom().pit();
2569 TextMetrics & tm = textMetrics(&buftext);
2570 int old_height = tm.parMetrics(bottom_pit).height();
2572 // make sure inline completion pointer is ok
2573 if (d->inlineCompletionPos_.fixIfBroken())
2574 d->inlineCompletionPos_ = DocIterator();
2576 // In Single Paragraph mode, rebreak only
2577 // the (main text, not inset!) paragraph containing the cursor.
2578 // (if this paragraph contains insets etc., rebreaking will
2579 // recursively descend)
2580 tm.redoParagraph(bottom_pit);
2581 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
2582 if (pm.height() != old_height)
2583 // Paragraph height has changed so we cannot proceed to
2584 // the singlePar optimisation.
2587 d->update_strategy_ = SingleParUpdate;
2589 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2590 << " y2: " << pm.position() + pm.descent()
2591 << " pit: " << bottom_pit
2592 << " singlepar: 1");
2597 void BufferView::updateMetrics()
2599 if (height_ == 0 || width_ == 0)
2602 Text & buftext = buffer_.text();
2603 pit_type const npit = int(buftext.paragraphs().size());
2605 // Clear out the position cache in case of full screen redraw,
2606 d->coord_cache_.clear();
2608 // Clear out paragraph metrics to avoid having invalid metrics
2609 // in the cache from paragraphs not relayouted below
2610 // The complete text metrics will be redone.
2611 d->text_metrics_.clear();
2613 TextMetrics & tm = textMetrics(&buftext);
2615 // make sure inline completion pointer is ok
2616 if (d->inlineCompletionPos_.fixIfBroken())
2617 d->inlineCompletionPos_ = DocIterator();
2619 if (d->anchor_pit_ >= npit)
2620 // The anchor pit must have been deleted...
2621 d->anchor_pit_ = npit - 1;
2623 // Rebreak anchor paragraph.
2624 tm.redoParagraph(d->anchor_pit_);
2625 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2628 if (d->anchor_pit_ == 0) {
2629 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2631 // Complete buffer visible? Then it's easy.
2632 if (scrollRange == 0)
2633 d->anchor_ypos_ = anchor_pm.ascent();
2635 // FIXME: Some clever handling needed to show
2636 // the _first_ paragraph up to the top if the cursor is
2637 // in the first line.
2639 anchor_pm.setPosition(d->anchor_ypos_);
2641 LYXERR(Debug::PAINTING, "metrics: "
2642 << " anchor pit = " << d->anchor_pit_
2643 << " anchor ypos = " << d->anchor_ypos_);
2645 // Redo paragraphs above anchor if necessary.
2646 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2647 // We are now just above the anchor paragraph.
2648 pit_type pit1 = d->anchor_pit_ - 1;
2649 for (; pit1 >= 0 && y1 >= 0; --pit1) {
2650 tm.redoParagraph(pit1);
2651 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2653 // Save the paragraph position in the cache.
2658 // Redo paragraphs below the anchor if necessary.
2659 int y2 = d->anchor_ypos_ + anchor_pm.descent();
2660 // We are now just below the anchor paragraph.
2661 pit_type pit2 = d->anchor_pit_ + 1;
2662 for (; pit2 < npit && y2 <= height_; ++pit2) {
2663 tm.redoParagraph(pit2);
2664 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2666 // Save the paragraph position in the cache.
2671 LYXERR(Debug::PAINTING, "Metrics: "
2672 << " anchor pit = " << d->anchor_pit_
2673 << " anchor ypos = " << d->anchor_ypos_
2676 << " pit1 = " << pit1
2677 << " pit2 = " << pit2);
2679 d->update_strategy_ = FullScreenUpdate;
2681 if (lyxerr.debugging(Debug::WORKAREA)) {
2682 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2683 d->coord_cache_.dump();
2688 void BufferView::insertLyXFile(FileName const & fname)
2690 LASSERT(d->cursor_.inTexted(), /**/);
2692 // Get absolute path of file and add ".lyx"
2693 // to the filename if necessary
2694 FileName filename = fileSearch(string(), fname.absFileName(), "lyx");
2696 docstring const disp_fn = makeDisplayPath(filename.absFileName());
2697 // emit message signal.
2698 message(bformat(_("Inserting document %1$s..."), disp_fn));
2701 Buffer buf(filename.absFileName(), false);
2702 if (buf.loadLyXFile() == Buffer::ReadSuccess) {
2703 ErrorList & el = buffer_.errorList("Parse");
2704 // Copy the inserted document error list into the current buffer one.
2705 el = buf.errorList("Parse");
2706 buffer_.undo().recordUndo(d->cursor_);
2707 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2708 buf.params().documentClassPtr(), el);
2709 res = _("Document %1$s inserted.");
2711 res = _("Could not insert document %1$s");
2714 buffer_.changed(true);
2715 // emit message signal.
2716 message(bformat(res, disp_fn));
2720 Point BufferView::coordOffset(DocIterator const & dit) const
2726 // Addup contribution of nested insets, from inside to outside,
2727 // keeping the outer paragraph for a special handling below
2728 for (size_t i = dit.depth() - 1; i >= 1; --i) {
2729 CursorSlice const & sl = dit[i];
2733 // get relative position inside sl.inset()
2734 sl.inset().cursorPos(*this, sl, dit.boundary() && (i + 1 == dit.depth()), xx, yy);
2736 // Make relative position inside of the edited inset relative to sl.inset()
2740 // In case of an RTL inset, the edited inset will be positioned to the left
2743 bool boundary_i = dit.boundary() && i + 1 == dit.depth();
2744 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2749 // remember width for the case that sl.inset() is positioned in an RTL inset
2750 if (i && dit[i - 1].text()) {
2751 // If this Inset is inside a Text Inset, retrieve the Dimension
2752 // from the containing text instead of using Inset::dimension() which
2753 // might not be implemented.
2754 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2755 // elimination of Inset::dim_ cache. This coordOffset() method needs
2756 // to be rewritten in light of the new design.
2757 Dimension const & dim = parMetrics(dit[i - 1].text(),
2758 dit[i - 1].pit()).insetDimension(&sl.inset());
2761 Dimension const dim = sl.inset().dimension(*this);
2765 //lyxerr << "Cursor::getPos, i: "
2766 // << i << " x: " << xx << " y: " << y << endl;
2769 // Add contribution of initial rows of outermost paragraph
2770 CursorSlice const & sl = dit[0];
2771 TextMetrics const & tm = textMetrics(sl.text());
2772 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2773 LASSERT(!pm.rows().empty(), /**/);
2774 y -= pm.rows()[0].ascent();
2776 // FIXME: document this mess
2778 if (sl.pos() > 0 && dit.depth() == 1) {
2780 if (pos && dit.boundary())
2782 // lyxerr << "coordOffset: boundary:" << dit.boundary() << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2783 rend = pm.pos2row(pos);
2785 rend = pm.pos2row(sl.pos());
2787 size_t rend = pm.pos2row(sl.pos());
2789 for (size_t rit = 0; rit != rend; ++rit)
2790 y += pm.rows()[rit].height();
2791 y += pm.rows()[rend].ascent();
2793 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2795 // Make relative position from the nested inset now bufferview absolute.
2796 int xx = bottom_tm.cursorX(dit.bottom(), dit.boundary() && dit.depth() == 1);
2799 // In the RTL case place the nested inset at the left of the cursor in
2800 // the outer paragraph
2801 bool boundary_1 = dit.boundary() && 1 == dit.depth();
2802 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2810 Point BufferView::getPos(DocIterator const & dit) const
2812 if (!paragraphVisible(dit))
2813 return Point(-1, -1);
2815 CursorSlice const & bot = dit.bottom();
2816 TextMetrics const & tm = textMetrics(bot.text());
2818 // offset from outer paragraph
2819 Point p = coordOffset(dit);
2820 p.y_ += tm.parMetrics(bot.pit()).position();
2825 bool BufferView::paragraphVisible(DocIterator const & dit) const
2827 CursorSlice const & bot = dit.bottom();
2828 TextMetrics const & tm = textMetrics(bot.text());
2830 return tm.contains(bot.pit());
2834 void BufferView::cursorPosAndHeight(Point & p, int & h) const
2836 Cursor const & cur = cursor();
2837 Font const font = cur.getFont();
2838 frontend::FontMetrics const & fm = theFontMetrics(font);
2839 int const asc = fm.maxAscent();
2840 int const des = fm.maxDescent();
2847 bool BufferView::cursorInView(Point const & p, int h) const
2849 Cursor const & cur = cursor();
2850 // does the cursor touch the screen ?
2851 if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
2857 void BufferView::draw(frontend::Painter & pain)
2859 if (height_ == 0 || width_ == 0)
2861 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2863 Text & text = buffer_.text();
2864 TextMetrics const & tm = d->text_metrics_[&text];
2865 int const y = tm.first().second->position();
2866 PainterInfo pi(this, pain);
2868 switch (d->update_strategy_) {
2870 case NoScreenUpdate:
2871 // If no screen painting is actually needed, only some the different
2872 // coordinates of insets and paragraphs needs to be updated.
2873 pi.full_repaint = true;
2874 pi.pain.setDrawingEnabled(false);
2878 case SingleParUpdate:
2879 pi.full_repaint = false;
2880 // In general, only the current row of the outermost paragraph
2881 // will be redrawn. Particular cases where selection spans
2882 // multiple paragraph are correctly detected in TextMetrics.
2886 case DecorationUpdate:
2887 // FIXME: We should also distinguish DecorationUpdate to avoid text
2888 // drawing if possible. This is not possible to do easily right now
2889 // because of the single backing pixmap.
2891 case FullScreenUpdate:
2892 // The whole screen, including insets, will be refreshed.
2893 pi.full_repaint = true;
2895 // Clear background.
2896 pain.fillRectangle(0, 0, width_, height_,
2897 pi.backgroundColor(&buffer_.inset()));
2902 // and possibly grey out below
2903 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2904 int const y2 = lastpm.second->position() + lastpm.second->descent();
2907 Color color = buffer().isInternal()
2908 ? Color_background : Color_bottomarea;
2909 pain.fillRectangle(0, y2, width_, height_ - y2, color);
2913 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
2915 // The scrollbar needs an update.
2918 // Normalize anchor for next time
2919 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2920 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2921 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2922 ParagraphMetrics const & pm = tm.parMetrics(pit);
2923 if (pm.position() + pm.descent() > 0) {
2924 d->anchor_pit_ = pit;
2925 d->anchor_ypos_ = pm.position();
2929 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2930 << " anchor ypos = " << d->anchor_ypos_);
2934 void BufferView::message(docstring const & msg)
2937 d->gui_->message(msg);
2941 void BufferView::showDialog(string const & name)
2944 d->gui_->showDialog(name, string());
2948 void BufferView::showDialog(string const & name,
2949 string const & data, Inset * inset)
2952 d->gui_->showDialog(name, data, inset);
2956 void BufferView::updateDialog(string const & name, string const & data)
2959 d->gui_->updateDialog(name, data);
2963 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2969 // FIXME: Move this out of BufferView again
2970 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2972 if (!fname.isReadableFile()) {
2973 docstring const error = from_ascii(strerror(errno));
2974 docstring const file = makeDisplayPath(fname.absFileName(), 50);
2975 docstring const text =
2976 bformat(_("Could not read the specified document\n"
2977 "%1$s\ndue to the error: %2$s"), file, error);
2978 Alert::error(_("Could not read file"), text);
2982 if (!fname.isReadableFile()) {
2983 docstring const file = makeDisplayPath(fname.absFileName(), 50);
2984 docstring const text =
2985 bformat(_("%1$s\n is not readable."), file);
2986 Alert::error(_("Could not open file"), text);
2990 // FIXME UNICODE: We don't know the encoding of the file
2991 docstring file_content = fname.fileContents("UTF-8");
2992 if (file_content.empty()) {
2993 Alert::error(_("Reading not UTF-8 encoded file"),
2994 _("The file is not UTF-8 encoded.\n"
2995 "It will be read as local 8Bit-encoded.\n"
2996 "If this does not give the correct result\n"
2997 "then please change the encoding of the file\n"
2998 "to UTF-8 with a program other than LyX.\n"));
2999 file_content = fname.fileContents("local8bit");
3002 return normalize_c(file_content);
3006 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
3008 docstring const tmpstr = contentsOfPlaintextFile(f);
3013 Cursor & cur = cursor();
3014 cap::replaceSelection(cur);
3015 buffer_.undo().recordUndo(cur);
3017 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
3019 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
3021 buffer_.changed(true);
3025 docstring const & BufferView::inlineCompletion() const
3027 return d->inlineCompletion_;
3031 size_t const & BufferView::inlineCompletionUniqueChars() const
3033 return d->inlineCompletionUniqueChars_;
3037 DocIterator const & BufferView::inlineCompletionPos() const
3039 return d->inlineCompletionPos_;
3043 void BufferView::resetInlineCompletionPos()
3045 d->inlineCompletionPos_ = DocIterator();
3049 bool samePar(DocIterator const & a, DocIterator const & b)
3051 if (a.empty() && b.empty())
3053 if (a.empty() || b.empty())
3055 if (a.depth() != b.depth())
3057 return &a.innerParagraph() == &b.innerParagraph();
3061 void BufferView::setInlineCompletion(Cursor const & cur, DocIterator const & pos,
3062 docstring const & completion, size_t uniqueChars)
3064 uniqueChars = min(completion.size(), uniqueChars);
3065 bool changed = d->inlineCompletion_ != completion
3066 || d->inlineCompletionUniqueChars_ != uniqueChars;
3067 bool singlePar = true;
3068 d->inlineCompletion_ = completion;
3069 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
3071 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
3074 DocIterator const & old = d->inlineCompletionPos_;
3076 //lyxerr << "inlineCompletionPos changed" << std::endl;
3077 // old or pos are in another paragraph?
3078 if ((!samePar(cur, pos) && !pos.empty())
3079 || (!samePar(cur, old) && !old.empty())) {
3081 //lyxerr << "different paragraph" << std::endl;
3083 d->inlineCompletionPos_ = pos;
3088 if (singlePar && !(cur.result().screenUpdate() & Update::Force))
3089 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
3091 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::Force);
3096 bool BufferView::clickableInset() const
3098 return d->clickable_inset_;