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"
48 #include "RowPainter.h"
51 #include "TextClass.h"
52 #include "TextMetrics.h"
54 #include "TocBackend.h"
55 #include "WordLangTuple.h"
57 #include "insets/InsetBibtex.h"
58 #include "insets/InsetCitation.h"
59 #include "insets/InsetCommand.h" // ChangeRefs
60 #include "insets/InsetExternal.h"
61 #include "insets/InsetGraphics.h"
62 #include "insets/InsetNote.h"
63 #include "insets/InsetRef.h"
64 #include "insets/InsetText.h"
66 #include "mathed/MathData.h"
68 #include "frontends/alert.h"
69 #include "frontends/Application.h"
70 #include "frontends/Delegates.h"
71 #include "frontends/FontMetrics.h"
72 #include "frontends/Painter.h"
73 #include "frontends/Selection.h"
75 #include "support/convert.h"
76 #include "support/debug.h"
77 #include "support/ExceptionMessage.h"
78 #include "support/filetools.h"
79 #include "support/gettext.h"
80 #include "support/lassert.h"
81 #include "support/lstrings.h"
82 #include "support/Package.h"
83 #include "support/types.h"
93 using namespace lyx::support;
97 namespace Alert = frontend::Alert;
101 /// Return an inset of this class if it exists at the current cursor position
103 T * getInsetByCode(Cursor const & cur, InsetCode code)
105 DocIterator it = cur;
106 Inset * inset = it.nextInset();
107 if (inset && inset->lyxCode() == code)
108 return static_cast<T*>(inset);
113 /// Note that comparing contents can only be used for InsetCommand
114 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
115 docstring const & contents)
117 DocIterator tmpdit = dit;
120 Inset const * inset = tmpdit.nextInset();
122 bool const valid_code = std::find(codes.begin(), codes.end(),
123 inset->lyxCode()) != codes.end();
124 InsetCommand const * ic = inset->asInsetCommand();
125 bool const same_or_no_contents = contents.empty()
126 || (ic && (ic->getFirstNonOptParam() == contents));
128 if (valid_code && same_or_no_contents) {
133 tmpdit.forwardInset();
140 /// Looks for next inset with one of the given codes.
141 /// Note that same_content can only be used for InsetCommand
142 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
146 DocIterator tmpdit = dit;
147 tmpdit.forwardInset();
151 Inset const * inset = tmpdit.nextInset();
152 if (same_content && inset) {
153 InsetCommand const * ic = inset->asInsetCommand();
155 bool const valid_code = std::find(codes.begin(), codes.end(),
156 ic->lyxCode()) != codes.end();
158 contents = ic->getFirstNonOptParam();
162 if (!findNextInset(tmpdit, codes, contents)) {
163 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
164 Inset * inset = &tmpdit.bottom().inset();
165 tmpdit = doc_iterator_begin(&inset->buffer(), inset);
166 if (!findNextInset(tmpdit, codes, contents))
178 /// Looks for next inset with the given code
179 void findInset(DocIterator & dit, InsetCode code, bool same_content)
181 findInset(dit, vector<InsetCode>(1, code), same_content);
185 /// Moves cursor to the next inset with one of the given codes.
186 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
189 Cursor tmpcur = bv->cursor();
190 if (!findInset(tmpcur, codes, same_content)) {
191 bv->cursor().message(_("No more insets"));
195 tmpcur.clearSelection();
196 bv->setCursor(tmpcur);
201 /// Moves cursor to the next inset with given code.
202 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
204 gotoInset(bv, vector<InsetCode>(1, code), same_content);
208 /// A map from a Text to the associated text metrics
209 typedef map<Text const *, TextMetrics> TextMetricsCache;
211 enum ScreenUpdateStrategy {
221 /////////////////////////////////////////////////////////////////////
225 /////////////////////////////////////////////////////////////////////
227 struct BufferView::Private
229 Private(BufferView & bv): wh_(0), cursor_(bv),
230 anchor_pit_(0), anchor_ypos_(0),
231 inlineCompletionUniqueChars_(0),
232 last_inset_(0), clickable_inset_(false),
233 mouse_position_cache_(),
234 bookmark_edit_position_(-1), gui_(0),
235 horiz_scroll_offset_(0)
239 ScrollbarParameters scrollbarParameters_;
241 ScreenUpdateStrategy update_strategy_;
243 CoordCache coord_cache_;
245 /// Estimated average par height for scrollbar.
247 /// this is used to handle XSelection events in the right manner.
256 pit_type anchor_pit_;
260 vector<int> par_height_;
263 DocIterator inlineCompletionPos_;
265 docstring inlineCompletion_;
267 size_t inlineCompletionUniqueChars_;
269 /// keyboard mapping object.
272 /// last visited inset.
273 /** kept to send setMouseHover(false).
274 * Not owned, so don't delete.
276 Inset const * last_inset_;
277 /// are we hovering something that we can click
278 bool clickable_inset_;
280 /// position of the mouse at the time of the last mouse move
281 /// This is used to update the hovering status of inset in
282 /// cases where the buffer is scrolled, but the mouse didn't move.
283 Point mouse_position_cache_;
285 // cache for id of the paragraph which was edited the last time
286 int bookmark_edit_position_;
288 mutable TextMetricsCache text_metrics_;
291 /** Not owned, so don't delete.
293 frontend::GuiBufferViewDelegate * gui_;
295 /// Cache for Find Next
296 FuncRequest search_request_cache_;
299 map<string, Inset *> edited_insets_;
301 /// When the row where the cursor lies is scrolled, this
302 /// contains the scroll offset
303 int horiz_scroll_offset_;
304 /// a slice pointing to the start of the row where the cursor
305 /// is (at last draw time)
306 CursorSlice current_row_slice_;
307 /// a slice pointing to the start of the row where cursor was
308 /// at previous draw event
309 CursorSlice last_row_slice_;
313 BufferView::BufferView(Buffer & buf)
314 : width_(0), height_(0), full_screen_(false), buffer_(buf),
315 d(new Private(*this))
317 d->xsel_cache_.set = false;
318 d->intl_.initKeyMapper(lyxrc.use_kbmap);
320 d->cursor_.setBuffer(&buf);
321 d->cursor_.push(buffer_.inset());
322 d->cursor_.resetAnchor();
323 d->cursor_.setCurrentFont();
325 buffer_.updatePreviews();
329 BufferView::~BufferView()
331 // current buffer is going to be switched-off, save cursor pos
332 // Ideally, the whole cursor stack should be saved, but session
333 // currently can only handle bottom (whole document) level pit and pos.
334 // That is to say, if a cursor is in a nested inset, it will be
335 // restore to the left of the top level inset.
336 LastFilePosSection::FilePos fp;
337 fp.pit = d->cursor_.bottom().pit();
338 fp.pos = d->cursor_.bottom().pos();
339 theSession().lastFilePos().save(buffer_.fileName(), fp);
342 d->last_inset_->setMouseHover(this, false);
348 int BufferView::rightMargin() const
350 // The additional test for the case the outliner is opened.
352 !lyxrc.full_screen_limit ||
353 width_ < lyxrc.full_screen_width + 20)
356 return (width_ - lyxrc.full_screen_width) / 2;
360 int BufferView::leftMargin() const
362 return rightMargin();
366 bool BufferView::isTopScreen() const
368 return d->scrollbarParameters_.position == d->scrollbarParameters_.min;
372 bool BufferView::isBottomScreen() const
374 return d->scrollbarParameters_.position == d->scrollbarParameters_.max;
378 Intl & BufferView::getIntl()
384 Intl const & BufferView::getIntl() const
390 CoordCache & BufferView::coordCache()
392 return d->coord_cache_;
396 CoordCache const & BufferView::coordCache() const
398 return d->coord_cache_;
402 Buffer & BufferView::buffer()
408 Buffer const & BufferView::buffer() const
414 bool BufferView::fitCursor()
416 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
417 frontend::FontMetrics const & fm =
418 theFontMetrics(d->cursor_.getFont().fontInfo());
419 int const asc = fm.maxAscent();
420 int const des = fm.maxDescent();
421 Point const p = getPos(d->cursor_);
422 if (p.y_ - asc >= 0 && p.y_ + des < height_)
429 void BufferView::processUpdateFlags(Update::flags flags)
431 // This is close to a hot-path.
432 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
433 << "[fitcursor = " << (flags & Update::FitCursor)
434 << ", forceupdate = " << (flags & Update::Force)
435 << ", singlepar = " << (flags & Update::SinglePar)
436 << "] buffer: " << &buffer_);
438 // FIXME Does this really need doing here? It's done in updateBuffer, and
439 // if the Buffer doesn't need updating, then do the macros?
440 buffer_.updateMacros();
442 // Now do the first drawing step if needed. This consists on updating
443 // the CoordCache in updateMetrics().
444 // The second drawing step is done in WorkArea::redraw() if needed.
446 // Case when no explicit update is requested.
448 // no need to redraw anything.
449 d->update_strategy_ = NoScreenUpdate;
453 if (flags == Update::Decoration) {
454 d->update_strategy_ = DecorationUpdate;
455 buffer_.changed(false);
459 if (flags == Update::FitCursor
460 || flags == (Update::Decoration | Update::FitCursor)) {
461 // tell the frontend to update the screen if needed.
466 if (flags & Update::Decoration) {
467 d->update_strategy_ = DecorationUpdate;
468 buffer_.changed(false);
471 // no screen update is needed in principle, but this
472 // could change if cursor row needs scrolling.
473 d->update_strategy_ = NoScreenUpdate;
474 buffer_.changed(false);
478 bool const full_metrics = flags & Update::Force || !singleParUpdate();
481 // We have to update the full screen metrics.
484 if (!(flags & Update::FitCursor)) {
485 // Nothing to do anymore. Trigger a redraw and return
486 buffer_.changed(false);
490 // updateMetrics() does not update paragraph position
491 // This is done at draw() time. So we need a redraw!
492 buffer_.changed(false);
495 // The cursor is off screen so ensure it is visible.
500 updateHoveredInset();
504 void BufferView::updateScrollbar()
506 if (height_ == 0 && width_ == 0)
509 // We prefer fixed size line scrolling.
510 d->scrollbarParameters_.single_step = defaultRowHeight();
511 // We prefer full screen page scrolling.
512 d->scrollbarParameters_.page_step = height_;
514 Text & t = buffer_.text();
515 TextMetrics & tm = d->text_metrics_[&t];
517 LYXERR(Debug::GUI, " Updating scrollbar: height: "
518 << t.paragraphs().size()
519 << " curr par: " << d->cursor_.bottom().pit()
520 << " default height " << defaultRowHeight());
522 size_t const parsize = t.paragraphs().size();
523 if (d->par_height_.size() != parsize) {
524 d->par_height_.clear();
525 // FIXME: We assume a default paragraph height of 2 rows. This
526 // should probably be pondered with the screen width.
527 d->par_height_.resize(parsize, defaultRowHeight() * 2);
530 // Look at paragraph heights on-screen
531 pair<pit_type, ParagraphMetrics const *> first = tm.first();
532 pair<pit_type, ParagraphMetrics const *> last = tm.last();
533 for (pit_type pit = first.first; pit <= last.first; ++pit) {
534 d->par_height_[pit] = tm.parMetrics(pit).height();
535 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
536 << d->par_height_[pit]);
539 int top_pos = first.second->position() - first.second->ascent();
540 int bottom_pos = last.second->position() + last.second->descent();
541 bool first_visible = first.first == 0 && top_pos >= 0;
542 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
543 if (first_visible && last_visible) {
544 d->scrollbarParameters_.min = 0;
545 d->scrollbarParameters_.max = 0;
549 d->scrollbarParameters_.min = top_pos;
550 for (size_t i = 0; i != size_t(first.first); ++i)
551 d->scrollbarParameters_.min -= d->par_height_[i];
552 d->scrollbarParameters_.max = bottom_pos;
553 for (size_t i = last.first + 1; i != parsize; ++i)
554 d->scrollbarParameters_.max += d->par_height_[i];
556 d->scrollbarParameters_.position = 0;
557 // The reference is the top position so we remove one page.
558 if (lyxrc.scroll_below_document)
559 d->scrollbarParameters_.max -= minVisiblePart();
561 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
565 ScrollbarParameters const & BufferView::scrollbarParameters() const
567 return d->scrollbarParameters_;
571 docstring BufferView::toolTip(int x, int y) const
573 // Get inset under mouse, if there is one.
574 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
576 // No inset, no tooltip...
578 return covering_inset->toolTip(*this, x, y);
582 string BufferView::contextMenu(int x, int y) const
584 //If there is a selection, return the containing inset menu
585 if (d->cursor_.selection())
586 return d->cursor_.inset().contextMenu(*this, x, y);
588 // Get inset under mouse, if there is one.
589 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
591 return covering_inset->contextMenu(*this, x, y);
593 return buffer_.inset().contextMenu(*this, x, y);
597 void BufferView::scrollDocView(int value, bool update)
599 int const offset = value - d->scrollbarParameters_.position;
601 // No scrolling at all? No need to redraw anything
605 // If the offset is less than 2 screen height, prefer to scroll instead.
606 if (abs(offset) <= 2 * height_) {
607 d->anchor_ypos_ -= offset;
608 buffer_.changed(true);
609 updateHoveredInset();
613 // cut off at the top
614 if (value <= d->scrollbarParameters_.min) {
615 DocIterator dit = doc_iterator_begin(&buffer_);
616 showCursor(dit, false, update);
617 LYXERR(Debug::SCROLLING, "scroll to top");
621 // cut off at the bottom
622 if (value >= d->scrollbarParameters_.max) {
623 DocIterator dit = doc_iterator_end(&buffer_);
625 showCursor(dit, false, update);
626 LYXERR(Debug::SCROLLING, "scroll to bottom");
630 // find paragraph at target position
631 int par_pos = d->scrollbarParameters_.min;
633 for (; i != int(d->par_height_.size()); ++i) {
634 par_pos += d->par_height_[i];
635 if (par_pos >= value)
639 if (par_pos < value) {
640 // It seems we didn't find the correct pit so stay on the safe side and
642 LYXERR0("scrolling position not found!");
643 scrollDocView(d->scrollbarParameters_.max, update);
647 DocIterator dit = doc_iterator_begin(&buffer_);
649 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
650 showCursor(dit, false, update);
654 // FIXME: this method is not working well.
655 void BufferView::setCursorFromScrollbar()
657 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
659 int const height = 2 * defaultRowHeight();
660 int const first = height;
661 int const last = height_ - height;
663 Cursor const & oldcur = d->cursor_;
665 switch (cursorStatus(oldcur)) {
673 int const y = getPos(oldcur).y_;
674 newy = min(last, max(y, first));
678 // We reset the cursor because cursorStatus() does not
679 // work when the cursor is within mathed.
682 tm.setCursorFromCoordinates(cur, 0, newy);
684 // update the bufferview cursor and notify insets
685 // FIXME: Care about the d->cursor_ flags to redraw if needed
686 Cursor old = d->cursor_;
688 // the DEPM call in mouseSetCursor() might have destroyed the
689 // paragraph the cursor is in.
690 bool badcursor = old.fixIfBroken();
691 badcursor |= notifyCursorLeavesOrEnters(old, d->cursor_);
693 d->cursor_.fixIfBroken();
697 Change const BufferView::getCurrentChange() const
699 if (!d->cursor_.selection())
700 return Change(Change::UNCHANGED);
702 DocIterator dit = d->cursor_.selectionBegin();
703 // The selected content might have been changed (see #7685)
704 while (dit.inMathed())
705 // Find enclosing text cursor
707 return dit.paragraph().lookupChange(dit.pos());
711 // this could be used elsewhere as well?
712 // FIXME: This does not work within mathed!
713 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
715 Point const p = getPos(dit);
718 if (p.y_ > workHeight())
724 void BufferView::bookmarkEditPosition()
726 // Don't eat cpu time for each keystroke
727 if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
730 d->bookmark_edit_position_ = d->cursor_.paragraph().id();
734 void BufferView::saveBookmark(unsigned int idx)
736 // tentatively save bookmark, id and pos will be used to
737 // acturately locate a bookmark in a 'live' lyx session.
738 // pit and pos will be updated with bottom level pit/pos
740 if (!buffer_.isInternal()) {
741 theSession().bookmarks().save(
743 d->cursor_.bottom().pit(),
744 d->cursor_.bottom().pos(),
745 d->cursor_.paragraph().id(),
750 // emit message signal.
751 message(_("Save bookmark"));
756 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
757 int top_id, pos_type top_pos)
759 bool success = false;
762 d->cursor_.clearSelection();
764 // if a valid par_id is given, try it first
765 // This is the case for a 'live' bookmark when unique paragraph ID
766 // is used to track bookmarks.
768 dit = buffer_.getParFromID(top_id);
770 dit.pos() = min(dit.paragraph().size(), top_pos);
771 // Some slices of the iterator may not be
772 // reachable (e.g. closed collapsable inset)
773 // so the dociterator may need to be
774 // shortened. Otherwise, setCursor may crash
775 // lyx when the cursor can not be set to these
777 size_t const n = dit.depth();
778 for (size_t i = 0; i < n; ++i)
779 if (!dit[i].inset().editable()) {
787 // if top_id == 0, or searching through top_id failed
788 // This is the case for a 'restored' bookmark when only bottom
789 // (document level) pit was saved. Because of this, bookmark
790 // restoration is inaccurate. If a bookmark was within an inset,
791 // it will be restored to the left of the outmost inset that contains
793 if (bottom_pit < int(buffer_.paragraphs().size())) {
794 dit = doc_iterator_begin(&buffer_);
796 dit.pit() = bottom_pit;
797 dit.pos() = min(bottom_pos, dit.paragraph().size());
802 // Note: only bottom (document) level pit is set.
804 // set the current font.
805 d->cursor_.setCurrentFont();
806 // To center the screen on this new position we need the
807 // paragraph position which is computed at draw() time.
808 // So we need a redraw!
809 buffer_.changed(false);
818 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
820 if (d->cursor_.real_current_font.isRightToLeft()) {
821 if (d->intl_.keymap == Intl::PRIMARY)
822 d->intl_.keyMapSec();
824 if (d->intl_.keymap == Intl::SECONDARY)
825 d->intl_.keyMapPrim();
828 d->intl_.getTransManager().translateAndInsert(c, t, cur);
832 int BufferView::workWidth() const
838 void BufferView::recenter()
840 showCursor(d->cursor_, true, true);
844 void BufferView::showCursor()
846 showCursor(d->cursor_, false, true);
850 void BufferView::showCursor(DocIterator const & dit,
851 bool recenter, bool update)
853 if (scrollToCursor(dit, recenter) && update) {
854 buffer_.changed(true);
855 updateHoveredInset();
860 void BufferView::scrollToCursor()
862 if (scrollToCursor(d->cursor_, false)) {
863 buffer_.changed(true);
864 updateHoveredInset();
869 bool BufferView::scrollToCursor(DocIterator const & dit, bool recenter)
871 // We are not properly started yet, delay until resizing is
876 LYXERR(Debug::SCROLLING, "recentering!");
878 CursorSlice const & bot = dit.bottom();
879 TextMetrics & tm = d->text_metrics_[bot.text()];
881 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
882 int bot_pit = bot.pit();
883 if (bot_pit > max_pit) {
884 // FIXME: Why does this happen?
885 LYXERR0("bottom pit is greater that max pit: "
886 << bot_pit << " > " << max_pit);
890 if (bot_pit == tm.first().first - 1)
891 tm.newParMetricsUp();
892 else if (bot_pit == tm.last().first + 1)
893 tm.newParMetricsDown();
895 if (tm.contains(bot_pit)) {
896 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
897 LBUFERR(!pm.rows().empty());
898 // FIXME: smooth scrolling doesn't work in mathed.
899 CursorSlice const & cs = dit.innerTextSlice();
900 int offset = coordOffset(dit).y_;
901 int ypos = pm.position() + offset;
902 Dimension const & row_dim =
903 pm.getRow(cs.pos(), dit.boundary()).dimension();
906 scrolled = scroll(ypos - height_/2);
908 // We try to visualize the whole row, if the row height is larger than
909 // the screen height, we scroll to a heuristic value of height_ / 4.
910 // FIXME: This heuristic value should be replaced by a recursive search
911 // for a row in the inset that can be visualized completely.
912 else if (row_dim.height() > height_) {
913 if (ypos < defaultRowHeight())
914 scrolled = scroll(ypos - height_ / 4);
915 else if (ypos > height_ - defaultRowHeight())
916 scrolled = scroll(ypos - 3 * height_ / 4);
919 // If the top part of the row falls of the screen, we scroll
920 // up to align the top of the row with the top of the screen.
921 else if (ypos - row_dim.ascent() < 0 && ypos < height_) {
922 int ynew = row_dim.ascent();
923 scrolled = scrollUp(ynew - ypos);
926 // If the bottom of the row falls of the screen, we scroll down.
927 else if (ypos + row_dim.descent() > height_ && ypos > 0) {
928 int ynew = height_ - row_dim.descent();
929 scrolled = scrollDown(ypos - ynew);
932 // else, nothing to do, the cursor is already visible so we just return.
933 return scrolled != 0;
936 // fix inline completion position
937 if (d->inlineCompletionPos_.fixIfBroken())
938 d->inlineCompletionPos_ = DocIterator();
940 tm.redoParagraph(bot_pit);
941 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
942 int offset = coordOffset(dit).y_;
944 d->anchor_pit_ = bot_pit;
945 CursorSlice const & cs = dit.innerTextSlice();
946 Dimension const & row_dim =
947 pm.getRow(cs.pos(), dit.boundary()).dimension();
950 d->anchor_ypos_ = height_/2;
951 else if (d->anchor_pit_ == 0)
952 d->anchor_ypos_ = offset + pm.ascent();
953 else if (d->anchor_pit_ == max_pit)
954 d->anchor_ypos_ = height_ - offset - row_dim.descent();
955 else if (offset > height_)
956 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
958 d->anchor_ypos_ = defaultRowHeight() * 2;
964 void BufferView::makeDocumentClass()
966 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
967 buffer_.params().makeDocumentClass();
968 updateDocumentClass(olddc);
972 void BufferView::updateDocumentClass(DocumentClassConstPtr olddc)
974 message(_("Converting document to new document class..."));
976 StableDocIterator backcur(d->cursor_);
977 ErrorList & el = buffer_.errorList("Class Switch");
978 cap::switchBetweenClasses(
979 olddc, buffer_.params().documentClassPtr(),
980 static_cast<InsetText &>(buffer_.inset()), el);
982 setCursor(backcur.asDocIterator(&buffer_));
984 buffer_.errors("Class Switch");
988 /** Return the change status at cursor position, taking in account the
989 * status at each level of the document iterator (a table in a deleted
990 * footnote is deleted).
991 * When \param outer is true, the top slice is not looked at.
993 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
995 size_t const depth = dit.depth() - (outer ? 1 : 0);
997 for (size_t i = 0 ; i < depth ; ++i) {
998 CursorSlice const & slice = dit[i];
999 if (!slice.inset().inMathed()
1000 && slice.pos() < slice.paragraph().size()) {
1001 Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
1002 if (ch != Change::UNCHANGED)
1006 return Change::UNCHANGED;
1010 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1012 FuncCode const act = cmd.action();
1014 // Can we use a readonly buffer?
1015 if (buffer_.isReadonly()
1016 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1017 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1018 flag.message(from_utf8(N_("Document is read-only")));
1019 flag.setEnabled(false);
1023 // Are we in a DELETED change-tracking region?
1024 if (lookupChangeType(d->cursor_, true) == Change::DELETED
1025 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1026 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1027 flag.message(from_utf8(N_("This portion of the document is deleted.")));
1028 flag.setEnabled(false);
1032 Cursor & cur = d->cursor_;
1034 if (cur.getStatus(cmd, flag))
1039 // FIXME: This is a bit problematic because we don't check if this is
1040 // a document BufferView or not for these LFUNs. We probably have to
1041 // dispatch both to currentBufferView() and, if that fails,
1042 // to documentBufferView(); same as we do now for current Buffer and
1043 // document Buffer. Ideally those LFUN should go to Buffer as they
1044 // operate on the full Buffer and the cursor is only needed either for
1045 // an Undo record or to restore a cursor position. But we don't know
1046 // how to do that inside Buffer of course.
1047 case LFUN_BUFFER_PARAMS_APPLY:
1048 case LFUN_LAYOUT_MODULES_CLEAR:
1049 case LFUN_LAYOUT_MODULE_ADD:
1050 case LFUN_LAYOUT_RELOAD:
1051 case LFUN_TEXTCLASS_APPLY:
1052 case LFUN_TEXTCLASS_LOAD:
1053 flag.setEnabled(!buffer_.isReadonly());
1057 // We do not use the LyXAction flag for readonly because Undo sets the
1058 // buffer clean/dirty status by itself.
1059 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasUndoStack());
1062 // We do not use the LyXAction flag for readonly because Redo sets the
1063 // buffer clean/dirty status by itself.
1064 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasRedoStack());
1066 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1067 case LFUN_FILE_INSERT_PLAINTEXT: {
1068 docstring const fname = cmd.argument();
1069 if (!FileName::isAbsolute(to_utf8(fname))) {
1070 flag.message(_("Absolute filename expected."));
1073 flag.setEnabled(cur.inTexted());
1076 case LFUN_FILE_INSERT:
1077 case LFUN_BOOKMARK_SAVE:
1078 // FIXME: Actually, these LFUNS should be moved to Text
1079 flag.setEnabled(cur.inTexted());
1082 case LFUN_FONT_STATE:
1083 case LFUN_LABEL_INSERT:
1084 case LFUN_INFO_INSERT:
1085 case LFUN_PARAGRAPH_GOTO:
1086 case LFUN_NOTE_NEXT:
1087 case LFUN_REFERENCE_NEXT:
1088 case LFUN_WORD_FIND:
1089 case LFUN_WORD_FIND_FORWARD:
1090 case LFUN_WORD_FIND_BACKWARD:
1091 case LFUN_WORD_REPLACE:
1094 case LFUN_MARK_TOGGLE:
1095 case LFUN_SCREEN_RECENTER:
1096 case LFUN_SCREEN_SHOW_CURSOR:
1097 case LFUN_BIBTEX_DATABASE_ADD:
1098 case LFUN_BIBTEX_DATABASE_DEL:
1099 case LFUN_STATISTICS:
1100 case LFUN_KEYMAP_OFF:
1101 case LFUN_KEYMAP_PRIMARY:
1102 case LFUN_KEYMAP_SECONDARY:
1103 case LFUN_KEYMAP_TOGGLE:
1104 flag.setEnabled(true);
1107 case LFUN_WORD_FINDADV: {
1108 FindAndReplaceOptions opt;
1109 istringstream iss(to_utf8(cmd.argument()));
1111 flag.setEnabled(opt.repl_buf_name.empty()
1112 || !buffer_.isReadonly());
1115 case LFUN_LABEL_GOTO: {
1116 flag.setEnabled(!cmd.argument().empty()
1117 || getInsetByCode<InsetRef>(cur, REF_CODE));
1121 case LFUN_CHANGES_TRACK:
1122 flag.setEnabled(true);
1123 flag.setOnOff(buffer_.params().track_changes);
1126 case LFUN_CHANGES_OUTPUT:
1127 flag.setEnabled(true);
1128 flag.setOnOff(buffer_.params().output_changes);
1131 case LFUN_CHANGES_MERGE:
1132 case LFUN_CHANGE_NEXT:
1133 case LFUN_CHANGE_PREVIOUS:
1134 case LFUN_ALL_CHANGES_ACCEPT:
1135 case LFUN_ALL_CHANGES_REJECT:
1136 // TODO: context-sensitive enabling of LFUNs
1137 // In principle, these command should only be enabled if there
1138 // is a change in the document. However, without proper
1139 // optimizations, this will inevitably result in poor performance.
1140 flag.setEnabled(true);
1143 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
1144 flag.setOnOff(buffer_.params().compressed);
1148 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC: {
1149 flag.setOnOff(buffer_.params().output_sync);
1153 case LFUN_SCREEN_UP:
1154 case LFUN_SCREEN_DOWN:
1156 case LFUN_SCREEN_UP_SELECT:
1157 case LFUN_SCREEN_DOWN_SELECT:
1158 case LFUN_INSET_FORALL:
1159 flag.setEnabled(true);
1162 case LFUN_LAYOUT_TABULAR:
1163 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1167 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1170 case LFUN_LAYOUT_PARAGRAPH:
1171 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1174 case LFUN_BRANCH_ADD_INSERT:
1175 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1178 case LFUN_DIALOG_SHOW_NEW_INSET:
1179 // FIXME: this is wrong, but I do not understand the
1181 if (cur.inset().lyxCode() == CAPTION_CODE)
1182 return cur.inset().getStatus(cur, cmd, flag);
1183 // FIXME we should consider passthru paragraphs too.
1184 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1187 case LFUN_CITATION_INSERT: {
1188 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1189 // FIXME: This could turn in a recursive hell.
1190 // Shouldn't we use Buffer::getStatus() instead?
1191 flag.setEnabled(lyx::getStatus(fr).enabled());
1194 case LFUN_INSET_APPLY: {
1195 string const name = cmd.getArg(0);
1196 Inset * inset = editedInset(name);
1198 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1199 if (!inset->getStatus(cur, fr, flag)) {
1200 // Every inset is supposed to handle this
1201 LASSERT(false, break);
1204 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1205 flag = lyx::getStatus(fr);
1218 Inset * BufferView::editedInset(string const & name) const
1220 map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1221 return it == d->edited_insets_.end() ? 0 : it->second;
1225 void BufferView::editInset(string const & name, Inset * inset)
1227 d->edited_insets_[name] = inset;
1231 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1233 LYXERR(Debug::ACTION, "BufferView::dispatch: cmd: " << cmd);
1235 string const argument = to_utf8(cmd.argument());
1236 Cursor & cur = d->cursor_;
1238 // Don't dispatch function that does not apply to internal buffers.
1239 if (buffer_.isInternal()
1240 && lyxaction.funcHasFlag(cmd.action(), LyXAction::NoInternal))
1243 // We'll set this back to false if need be.
1244 bool dispatched = true;
1245 buffer_.undo().beginUndoGroup();
1247 FuncCode const act = cmd.action();
1250 case LFUN_BUFFER_PARAMS_APPLY: {
1251 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
1252 cur.recordUndoFullDocument();
1253 istringstream ss(to_utf8(cmd.argument()));
1256 int const unknown_tokens = buffer_.readHeader(lex);
1257 if (unknown_tokens != 0) {
1258 LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1259 << unknown_tokens << " unknown token"
1260 << (unknown_tokens == 1 ? "" : "s"));
1262 updateDocumentClass(olddc);
1264 // We are most certainly here because of a change in the document
1265 // It is then better to make sure that all dialogs are in sync with
1266 // current document settings.
1267 dr.screenUpdate(Update::Force | Update::FitCursor);
1268 dr.forceBufferUpdate();
1272 case LFUN_LAYOUT_MODULES_CLEAR: {
1273 cur.recordUndoFullDocument();
1274 buffer_.params().clearLayoutModules();
1275 makeDocumentClass();
1276 dr.screenUpdate(Update::Force);
1277 dr.forceBufferUpdate();
1281 case LFUN_LAYOUT_MODULE_ADD: {
1282 BufferParams const & params = buffer_.params();
1283 if (!params.layoutModuleCanBeAdded(argument)) {
1284 LYXERR0("Module `" << argument <<
1285 "' cannot be added due to failed requirements or "
1286 "conflicts with installed modules.");
1289 cur.recordUndoFullDocument();
1290 buffer_.params().addLayoutModule(argument);
1291 makeDocumentClass();
1292 dr.screenUpdate(Update::Force);
1293 dr.forceBufferUpdate();
1297 case LFUN_TEXTCLASS_APPLY: {
1298 // since this shortcircuits, the second call is made only if
1300 bool const success =
1301 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1302 LayoutFileList::get().load(argument, buffer_.filePath());
1304 docstring s = bformat(_("The document class `%1$s' "
1305 "could not be loaded."), from_utf8(argument));
1306 frontend::Alert::error(_("Could not load class"), s);
1310 LayoutFile const * old_layout = buffer_.params().baseClass();
1311 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1313 if (old_layout == new_layout)
1317 // Save the old, possibly modular, layout for use in conversion.
1318 cur.recordUndoFullDocument();
1319 buffer_.params().setBaseClass(argument);
1320 makeDocumentClass();
1321 dr.screenUpdate(Update::Force);
1322 dr.forceBufferUpdate();
1326 case LFUN_TEXTCLASS_LOAD: {
1327 // since this shortcircuits, the second call is made only if
1329 bool const success =
1330 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1331 LayoutFileList::get().load(argument, buffer_.filePath());
1333 docstring s = bformat(_("The document class `%1$s' "
1334 "could not be loaded."), from_utf8(argument));
1335 frontend::Alert::error(_("Could not load class"), s);
1340 case LFUN_LAYOUT_RELOAD: {
1341 LayoutFileIndex bc = buffer_.params().baseClassID();
1342 LayoutFileList::get().reset(bc);
1343 buffer_.params().setBaseClass(bc);
1344 makeDocumentClass();
1345 dr.screenUpdate(Update::Force);
1346 dr.forceBufferUpdate();
1351 dr.setMessage(_("Undo"));
1352 cur.clearSelection();
1353 if (!cur.textUndo())
1354 dr.setMessage(_("No further undo information"));
1356 dr.screenUpdate(Update::Force | Update::FitCursor);
1357 dr.forceBufferUpdate();
1361 dr.setMessage(_("Redo"));
1362 cur.clearSelection();
1363 if (!cur.textRedo())
1364 dr.setMessage(_("No further redo information"));
1366 dr.screenUpdate(Update::Force | Update::FitCursor);
1367 dr.forceBufferUpdate();
1370 case LFUN_FONT_STATE:
1371 dr.setMessage(cur.currentState());
1374 case LFUN_BOOKMARK_SAVE:
1375 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1378 case LFUN_LABEL_GOTO: {
1379 docstring label = cmd.argument();
1380 if (label.empty()) {
1382 getInsetByCode<InsetRef>(cur, REF_CODE);
1384 label = inset->getParam("reference");
1385 // persistent=false: use temp_bookmark
1389 if (!label.empty()) {
1391 // at the moment, this is redundant, since gotoLabel will
1392 // eventually call LFUN_PARAGRAPH_GOTO, but it seems best
1394 dr.screenUpdate(Update::Force | Update::FitCursor);
1399 case LFUN_PARAGRAPH_GOTO: {
1400 int const id = convert<int>(cmd.getArg(0));
1401 int const pos = convert<int>(cmd.getArg(1));
1403 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1404 b = theBufferList().next(b)) {
1406 DocIterator dit = b->getParFromID(id);
1408 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1412 LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1413 << " found in buffer `"
1414 << b->absFileName() << "'.");
1416 if (b == &buffer_) {
1420 dr.screenUpdate(Update::Force | Update::FitCursor);
1422 // Switch to other buffer view and resend cmd
1423 lyx::dispatch(FuncRequest(
1424 LFUN_BUFFER_SWITCH, b->absFileName()));
1432 case LFUN_NOTE_NEXT:
1433 gotoInset(this, NOTE_CODE, false);
1436 case LFUN_REFERENCE_NEXT: {
1437 vector<InsetCode> tmp;
1438 tmp.push_back(LABEL_CODE);
1439 tmp.push_back(REF_CODE);
1440 gotoInset(this, tmp, true);
1444 case LFUN_CHANGES_TRACK:
1445 buffer_.params().track_changes = !buffer_.params().track_changes;
1448 case LFUN_CHANGES_OUTPUT:
1449 buffer_.params().output_changes = !buffer_.params().output_changes;
1450 if (buffer_.params().output_changes) {
1451 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1452 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1453 LaTeXFeatures::isAvailable("xcolor");
1455 if (!dvipost && !xcolorulem) {
1456 Alert::warning(_("Changes not shown in LaTeX output"),
1457 _("Changes will not be highlighted in LaTeX output, "
1458 "because neither dvipost nor xcolor/ulem are installed.\n"
1459 "Please install these packages or redefine "
1460 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1461 } else if (!xcolorulem) {
1462 Alert::warning(_("Changes not shown in LaTeX output"),
1463 _("Changes will not be highlighted in LaTeX output "
1464 "when using pdflatex, because xcolor and ulem are not installed.\n"
1465 "Please install both packages or redefine "
1466 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1471 case LFUN_CHANGE_NEXT:
1472 findNextChange(this);
1473 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1474 dr.screenUpdate(Update::Force | Update::FitCursor);
1477 case LFUN_CHANGE_PREVIOUS:
1478 findPreviousChange(this);
1479 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1480 dr.screenUpdate(Update::Force | Update::FitCursor);
1483 case LFUN_CHANGES_MERGE:
1484 if (findNextChange(this) || findPreviousChange(this)) {
1485 dr.screenUpdate(Update::Force | Update::FitCursor);
1486 dr.forceBufferUpdate();
1487 showDialog("changes");
1491 case LFUN_ALL_CHANGES_ACCEPT:
1492 // select complete document
1494 cur.selHandle(true);
1495 buffer_.text().cursorBottom(cur);
1496 // accept everything in a single step to support atomic undo
1497 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1499 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1500 dr.screenUpdate(Update::Force | Update::FitCursor);
1501 dr.forceBufferUpdate();
1504 case LFUN_ALL_CHANGES_REJECT:
1505 // select complete document
1507 cur.selHandle(true);
1508 buffer_.text().cursorBottom(cur);
1509 // reject everything in a single step to support atomic undo
1510 // Note: reject does not work recursively; the user may have to repeat the operation
1511 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1513 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1514 dr.screenUpdate(Update::Force | Update::FitCursor);
1515 dr.forceBufferUpdate();
1518 case LFUN_WORD_FIND_FORWARD:
1519 case LFUN_WORD_FIND_BACKWARD: {
1521 // Would it maybe be better if this variable were view specific anyway?
1522 static docstring last_search;
1523 docstring searched_string;
1525 if (!cmd.argument().empty()) {
1526 last_search = cmd.argument();
1527 searched_string = cmd.argument();
1529 searched_string = last_search;
1532 if (searched_string.empty())
1535 bool const fw = act == LFUN_WORD_FIND_FORWARD;
1536 docstring const data =
1537 find2string(searched_string, true, false, fw);
1538 bool found = lyxfind(this, FuncRequest(LFUN_WORD_FIND, data));
1540 dr.screenUpdate(Update::Force | Update::FitCursor);
1550 case LFUN_WORD_FIND: {
1551 FuncRequest req = cmd;
1552 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1553 req = d->search_request_cache_;
1554 if (req.argument().empty()) {
1555 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1558 if (lyxfind(this, req)) {
1559 dr.screenUpdate(Update::Force | Update::FitCursor);
1566 d->search_request_cache_ = req;
1570 case LFUN_WORD_REPLACE: {
1571 bool has_deleted = false;
1572 if (cur.selection()) {
1573 DocIterator beg = cur.selectionBegin();
1574 DocIterator end = cur.selectionEnd();
1575 if (beg.pit() == end.pit()) {
1576 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1577 if (!cur.inMathed() && cur.paragraph().isDeleted(p)) {
1584 if (lyxreplace(this, cmd, has_deleted)) {
1585 dr.forceBufferUpdate();
1586 dr.screenUpdate(Update::Force | Update::FitCursor);
1596 case LFUN_WORD_FINDADV: {
1597 FindAndReplaceOptions opt;
1598 istringstream iss(to_utf8(cmd.argument()));
1600 if (findAdv(this, opt)) {
1601 dr.screenUpdate(Update::Force | Update::FitCursor);
1612 cur.clearSelection();
1613 dr.setMessage(from_utf8(N_("Mark off")));
1617 cur.clearSelection();
1619 dr.setMessage(from_utf8(N_("Mark on")));
1622 case LFUN_MARK_TOGGLE:
1623 cur.setSelection(false);
1626 dr.setMessage(from_utf8(N_("Mark removed")));
1629 dr.setMessage(from_utf8(N_("Mark set")));
1634 case LFUN_SCREEN_SHOW_CURSOR:
1638 case LFUN_SCREEN_RECENTER:
1642 case LFUN_BIBTEX_DATABASE_ADD: {
1643 Cursor tmpcur = cur;
1644 findInset(tmpcur, BIBTEX_CODE, false);
1645 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1648 if (inset->addDatabase(cmd.argument())) {
1649 buffer_.invalidateBibfileCache();
1650 dr.forceBufferUpdate();
1656 case LFUN_BIBTEX_DATABASE_DEL: {
1657 Cursor tmpcur = cur;
1658 findInset(tmpcur, BIBTEX_CODE, false);
1659 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1662 if (inset->delDatabase(cmd.argument())) {
1663 buffer_.invalidateBibfileCache();
1664 dr.forceBufferUpdate();
1670 case LFUN_STATISTICS: {
1671 DocIterator from, to;
1672 if (cur.selection()) {
1673 from = cur.selectionBegin();
1674 to = cur.selectionEnd();
1676 from = doc_iterator_begin(&buffer_);
1677 to = doc_iterator_end(&buffer_);
1679 buffer_.updateStatistics(from, to);
1680 int const words = buffer_.wordCount();
1681 int const chars = buffer_.charCount(false);
1682 int const chars_blanks = buffer_.charCount(true);
1684 if (cur.selection())
1685 message = _("Statistics for the selection:");
1687 message = _("Statistics for the document:");
1690 message += bformat(_("%1$d words"), words);
1692 message += _("One word");
1694 if (chars_blanks != 1)
1695 message += bformat(_("%1$d characters (including blanks)"),
1698 message += _("One character (including blanks)");
1701 message += bformat(_("%1$d characters (excluding blanks)"),
1704 message += _("One character (excluding blanks)");
1706 Alert::information(_("Statistics"), message);
1710 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1711 // turn compression on/off
1712 buffer_.params().compressed = !buffer_.params().compressed;
1715 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
1716 buffer_.params().output_sync = !buffer_.params().output_sync;
1719 case LFUN_SCREEN_UP:
1720 case LFUN_SCREEN_DOWN: {
1721 Point p = getPos(cur);
1722 // This code has been commented out to enable to scroll down a
1723 // document, even if there are large insets in it (see bug #5465).
1724 /*if (p.y_ < 0 || p.y_ > height_) {
1725 // The cursor is off-screen so recenter before proceeding.
1729 int const scrolled = scroll(act == LFUN_SCREEN_UP
1730 ? -height_ : height_);
1731 if (act == LFUN_SCREEN_UP && scrolled > -height_)
1733 if (act == LFUN_SCREEN_DOWN && scrolled < height_)
1734 p = Point(width_, height_);
1736 bool const in_texted = cur.inTexted();
1737 cur.setCursor(doc_iterator_begin(cur.buffer()));
1738 cur.selHandle(false);
1739 buffer_.changed(true);
1740 updateHoveredInset();
1742 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1743 true, act == LFUN_SCREEN_UP);
1744 //FIXME: what to do with cur.x_target()?
1745 bool update = in_texted && cur.bv().checkDepm(cur, old);
1748 if (update || cur.mark())
1749 dr.screenUpdate(Update::Force | Update::FitCursor);
1751 dr.forceBufferUpdate();
1756 string const scroll_type = cmd.getArg(0);
1757 int scroll_step = 0;
1758 if (scroll_type == "line")
1759 scroll_step = d->scrollbarParameters_.single_step;
1760 else if (scroll_type == "page")
1761 scroll_step = d->scrollbarParameters_.page_step;
1764 string const scroll_quantity = cmd.getArg(1);
1765 if (scroll_quantity == "up")
1766 scrollUp(scroll_step);
1767 else if (scroll_quantity == "down")
1768 scrollDown(scroll_step);
1770 int const scroll_value = convert<int>(scroll_quantity);
1772 scroll(scroll_step * scroll_value);
1774 buffer_.changed(true);
1775 updateHoveredInset();
1776 dr.forceBufferUpdate();
1780 case LFUN_SCREEN_UP_SELECT: {
1781 // FIXME: why is the algorithm different from LFUN_SCREEN_UP?
1782 cur.selHandle(true);
1783 if (isTopScreen()) {
1784 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1788 int y = getPos(cur).y_;
1789 int const ymin = y - height_ + defaultRowHeight();
1790 while (y > ymin && cur.up())
1794 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1798 case LFUN_SCREEN_DOWN_SELECT: {
1799 // FIXME: why is the algorithm different from LFUN_SCREEN_DOWN?
1800 cur.selHandle(true);
1801 if (isBottomScreen()) {
1802 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1806 int y = getPos(cur).y_;
1807 int const ymax = y + height_ - defaultRowHeight();
1808 while (y < ymax && cur.down())
1812 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1817 // This would be in Buffer class if only Cursor did not
1818 // require a bufferview
1819 case LFUN_INSET_FORALL: {
1820 docstring const name = from_utf8(cmd.getArg(0));
1821 string const commandstr = cmd.getLongArg(1);
1822 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
1824 // an arbitrary number to limit number of iterations
1825 const int max_iter = 100000;
1827 Cursor & cur = d->cursor_;
1828 Cursor const savecur = cur;
1830 if (!cur.nextInset())
1832 cur.beginUndoGroup();
1833 while(cur && iterations < max_iter) {
1834 Inset * const ins = cur.nextInset();
1837 docstring insname = ins->layoutName();
1838 while (!insname.empty()) {
1839 if (insname == name || name == from_utf8("*")) {
1841 lyx::dispatch(fr, dr);
1845 size_t const i = insname.rfind(':');
1846 if (i == string::npos)
1848 insname = insname.substr(0, i);
1850 // if we did not delete the inset, skip it
1851 if (!cur.nextInset() || cur.nextInset() == ins)
1857 dr.screenUpdate(Update::Force);
1858 dr.forceBufferUpdate();
1860 if (iterations >= max_iter) {
1862 dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
1864 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
1869 case LFUN_BRANCH_ADD_INSERT: {
1870 docstring branch_name = from_utf8(cmd.getArg(0));
1871 if (branch_name.empty())
1872 if (!Alert::askForText(branch_name, _("Branch name")) ||
1873 branch_name.empty())
1876 DispatchResult drtmp;
1877 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
1878 if (drtmp.error()) {
1879 Alert::warning(_("Branch already exists"), drtmp.message());
1882 BranchList & branch_list = buffer_.params().branchlist();
1883 vector<docstring> const branches =
1884 getVectorFromString(branch_name, branch_list.separator());
1885 for (vector<docstring>::const_iterator it = branches.begin();
1886 it != branches.end(); ++it) {
1888 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch_name));
1893 case LFUN_KEYMAP_OFF:
1894 getIntl().keyMapOn(false);
1897 case LFUN_KEYMAP_PRIMARY:
1898 getIntl().keyMapPrim();
1901 case LFUN_KEYMAP_SECONDARY:
1902 getIntl().keyMapSec();
1905 case LFUN_KEYMAP_TOGGLE:
1906 getIntl().toggleKeyMap();
1909 case LFUN_DIALOG_SHOW_NEW_INSET: {
1910 string const name = cmd.getArg(0);
1911 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1912 if (decodeInsetParam(name, data, buffer_))
1913 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1915 lyxerr << "Inset type '" << name <<
1916 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
1920 case LFUN_CITATION_INSERT: {
1921 if (argument.empty()) {
1922 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1925 // we can have one optional argument, delimited by '|'
1926 // citation-insert <key>|<text_before>
1927 // this should be enhanced to also support text_after
1928 // and citation style
1929 string arg = argument;
1931 if (contains(argument, "|")) {
1932 arg = token(argument, '|', 0);
1933 opt1 = token(argument, '|', 1);
1936 // if our cursor is directly in front of or behind a citation inset,
1937 // we will instead add the new key to it.
1938 Inset * inset = cur.nextInset();
1939 if (!inset || inset->lyxCode() != CITE_CODE)
1940 inset = cur.prevInset();
1941 if (inset && inset->lyxCode() == CITE_CODE) {
1942 InsetCitation * icite = static_cast<InsetCitation *>(inset);
1943 if (icite->addKey(arg)) {
1944 dr.forceBufferUpdate();
1945 dr.screenUpdate(Update::FitCursor | Update::SinglePar);
1947 LYXERR0("Discarding optional argument to citation-insert.");
1952 InsetCommandParams icp(CITE_CODE);
1953 icp["key"] = from_utf8(arg);
1955 icp["before"] = from_utf8(opt1);
1956 string icstr = InsetCommand::params2string(icp);
1957 FuncRequest fr(LFUN_INSET_INSERT, icstr);
1962 case LFUN_INSET_APPLY: {
1963 string const name = cmd.getArg(0);
1964 Inset * inset = editedInset(name);
1966 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1970 // put cursor in front of inset.
1971 if (!setCursorFromInset(inset)) {
1972 LASSERT(false, break);
1975 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1976 inset->dispatch(cur, fr);
1977 dr.screenUpdate(cur.result().screenUpdate());
1978 if (cur.result().needBufferUpdate())
1979 dr.forceBufferUpdate();
1984 // The change of language of buffer belongs to the Buffer class.
1985 // We have to do it here because we need a cursor for Undo.
1986 // When Undo::recordUndoBufferParams() is implemented someday
1987 // LFUN_BUFFER_LANGUAGE should be handled by the Buffer class.
1988 case LFUN_BUFFER_LANGUAGE: {
1989 Language const * oldL = buffer_.params().language;
1990 Language const * newL = languages.getLanguage(argument);
1991 if (!newL || oldL == newL)
1993 if (oldL->rightToLeft() == newL->rightToLeft()) {
1994 cur.recordUndoFullDocument();
1995 buffer_.changeLanguage(oldL, newL);
1996 cur.setCurrentFont();
1997 dr.forceBufferUpdate();
2002 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2003 case LFUN_FILE_INSERT_PLAINTEXT: {
2004 bool const as_paragraph = (act == LFUN_FILE_INSERT_PLAINTEXT_PARA);
2005 string const fname = to_utf8(cmd.argument());
2006 if (!FileName::isAbsolute(fname))
2007 dr.setMessage(_("Absolute filename expected."));
2009 insertPlaintextFile(FileName(fname), as_paragraph);
2014 // OK, so try the Buffer itself...
2015 buffer_.dispatch(cmd, dr);
2016 dispatched = dr.dispatched();
2020 buffer_.undo().endUndoGroup();
2021 dr.dispatched(dispatched);
2025 docstring const BufferView::requestSelection()
2027 Cursor & cur = d->cursor_;
2029 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
2030 if (!cur.selection()) {
2031 d->xsel_cache_.set = false;
2035 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
2036 if (!d->xsel_cache_.set ||
2037 cur.top() != d->xsel_cache_.cursor ||
2038 cur.realAnchor().top() != d->xsel_cache_.anchor)
2040 d->xsel_cache_.cursor = cur.top();
2041 d->xsel_cache_.anchor = cur.realAnchor().top();
2042 d->xsel_cache_.set = cur.selection();
2043 return cur.selectionAsString(false);
2049 void BufferView::clearSelection()
2051 d->cursor_.clearSelection();
2052 // Clear the selection buffer. Otherwise a subsequent
2053 // middle-mouse-button paste would use the selection buffer,
2054 // not the more current external selection.
2055 cap::clearSelection();
2056 d->xsel_cache_.set = false;
2057 // The buffer did not really change, but this causes the
2058 // redraw we need because we cleared the selection above.
2059 buffer_.changed(false);
2063 void BufferView::resize(int width, int height)
2065 // Update from work area
2069 // Clear the paragraph height cache.
2070 d->par_height_.clear();
2071 // Redo the metrics.
2076 Inset const * BufferView::getCoveringInset(Text const & text,
2079 TextMetrics & tm = d->text_metrics_[&text];
2080 Inset * inset = tm.checkInsetHit(x, y);
2084 if (!inset->descendable(*this))
2085 // No need to go further down if the inset is not
2089 size_t cell_number = inset->nargs();
2090 // Check all the inner cell.
2091 for (size_t i = 0; i != cell_number; ++i) {
2092 Text const * inner_text = inset->getText(i);
2095 Inset const * inset_deeper =
2096 getCoveringInset(*inner_text, x, y);
2098 return inset_deeper;
2106 void BufferView::updateHoveredInset() const
2108 // Get inset under mouse, if there is one.
2109 int const x = d->mouse_position_cache_.x_;
2110 int const y = d->mouse_position_cache_.y_;
2111 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
2113 d->clickable_inset_ = covering_inset && covering_inset->clickable(x, y);
2115 if (covering_inset == d->last_inset_)
2116 // Same inset, no need to do anything...
2119 bool need_redraw = false;
2120 if (d->last_inset_) {
2121 // Remove the hint on the last hovered inset (if any).
2122 need_redraw |= d->last_inset_->setMouseHover(this, false);
2126 if (covering_inset && covering_inset->setMouseHover(this, true)) {
2128 // Only the insets that accept the hover state, do
2129 // clear the last_inset_, so only set the last_inset_
2130 // member if the hovered setting is accepted.
2131 d->last_inset_ = covering_inset;
2135 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
2136 << d->mouse_position_cache_.x_ << ", "
2137 << d->mouse_position_cache_.y_ << ")");
2139 d->update_strategy_ = DecorationUpdate;
2141 // This event (moving without mouse click) is not passed further.
2142 // This should be changed if it is further utilized.
2143 buffer_.changed(false);
2148 void BufferView::clearLastInset(Inset * inset) const
2150 if (d->last_inset_ != inset) {
2151 LYXERR0("Wrong last_inset!");
2158 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
2160 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
2162 // This is only called for mouse related events including
2163 // LFUN_FILE_OPEN generated by drag-and-drop.
2164 FuncRequest cmd = cmd0;
2166 Cursor old = cursor();
2168 cur.push(buffer_.inset());
2169 cur.setSelection(d->cursor_.selection());
2171 // Either the inset under the cursor or the
2172 // surrounding Text will handle this event.
2174 // make sure we stay within the screen...
2175 cmd.set_y(min(max(cmd.y(), -1), height_));
2177 d->mouse_position_cache_.x_ = cmd.x();
2178 d->mouse_position_cache_.y_ = cmd.y();
2180 if (cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
2181 updateHoveredInset();
2185 // Build temporary cursor.
2186 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x(), cmd.y());
2188 // Put anchor at the same position.
2191 cur.beginUndoGroup();
2193 // Try to dispatch to an non-editable inset near this position
2194 // via the temp cursor. If the inset wishes to change the real
2195 // cursor it has to do so explicitly by using
2196 // cur.bv().cursor() = cur; (or similar)
2198 inset->dispatch(cur, cmd);
2200 // Now dispatch to the temporary cursor. If the real cursor should
2201 // be modified, the inset's dispatch has to do so explicitly.
2202 if (!inset || !cur.result().dispatched())
2207 // Notify left insets
2209 bool badcursor = old.fixIfBroken() | cur.fixIfBroken();
2210 badcursor |= notifyCursorLeavesOrEnters(old, cur);
2212 cursor().fixIfBroken();
2215 // Do we have a selection?
2216 theSelection().haveSelection(cursor().selection());
2218 if (cur.needBufferUpdate()) {
2219 cur.clearBufferUpdate();
2220 buffer().updateBuffer();
2223 // If the command has been dispatched,
2224 if (cur.result().dispatched() || cur.result().screenUpdate())
2225 processUpdateFlags(cur.result().screenUpdate());
2229 int BufferView::minVisiblePart()
2231 return 2 * defaultRowHeight();
2235 int BufferView::scroll(int y)
2238 return scrollDown(y);
2240 return scrollUp(-y);
2245 int BufferView::scrollDown(int offset)
2247 Text * text = &buffer_.text();
2248 TextMetrics & tm = d->text_metrics_[text];
2249 int const ymax = height_ + offset;
2251 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2252 int bottom_pos = last.second->position() + last.second->descent();
2253 if (lyxrc.scroll_below_document)
2254 bottom_pos += height_ - minVisiblePart();
2255 if (last.first + 1 == int(text->paragraphs().size())) {
2256 if (bottom_pos <= height_)
2258 offset = min(offset, bottom_pos - height_);
2261 if (bottom_pos > ymax)
2263 tm.newParMetricsDown();
2265 d->anchor_ypos_ -= offset;
2270 int BufferView::scrollUp(int offset)
2272 Text * text = &buffer_.text();
2273 TextMetrics & tm = d->text_metrics_[text];
2274 int ymin = - offset;
2276 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2277 int top_pos = first.second->position() - first.second->ascent();
2278 if (first.first == 0) {
2281 offset = min(offset, - top_pos);
2286 tm.newParMetricsUp();
2288 d->anchor_ypos_ += offset;
2293 void BufferView::setCursorFromRow(int row)
2297 pit_type newpit = 0;
2298 pos_type newpos = 0;
2300 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
2302 bool posvalid = (tmpid != -1);
2304 // we need to make sure that the row and position
2305 // we got back are valid, because the buffer may well
2306 // have changed since we last generated the LaTeX.
2307 DocIterator dit = buffer_.getParFromID(tmpid);
2308 if (dit == doc_iterator_end(&buffer_))
2310 else if (dit.depth() > 1) {
2311 // We are in an inset.
2312 pos_type lastpos = dit.lastpos();
2313 dit.pos() = tmppos > lastpos ? lastpos : tmppos;
2319 // now have to check pos.
2321 Paragraph const & par = buffer_.text().getPar(newpit);
2322 if (newpos > par.size()) {
2323 LYXERR0("Requested position no longer valid.");
2324 newpos = par.size() - 1;
2329 frontend::Alert::error(_("Inverse Search Failed"),
2330 _("Invalid position requested by inverse search.\n"
2331 "You need to update the viewed document."));
2335 buffer_.text().setCursor(d->cursor_, newpit, newpos);
2336 d->cursor_.setSelection(false);
2337 d->cursor_.resetAnchor();
2342 bool BufferView::setCursorFromInset(Inset const * inset)
2344 // are we already there?
2345 if (cursor().nextInset() == inset)
2348 // Inset is not at cursor position. Find it in the document.
2351 while (cur && cur.nextInset() != inset)
2362 void BufferView::gotoLabel(docstring const & label)
2364 ListOfBuffers bufs = buffer().allRelatives();
2365 ListOfBuffers::iterator it = bufs.begin();
2366 for (; it != bufs.end(); ++it) {
2367 Buffer const * buf = *it;
2370 Toc & toc = buf->tocBackend().toc("label");
2371 TocIterator toc_it = toc.begin();
2372 TocIterator end = toc.end();
2373 for (; toc_it != end; ++toc_it) {
2374 if (label == toc_it->str()) {
2375 lyx::dispatch(toc_it->action());
2383 TextMetrics const & BufferView::textMetrics(Text const * t) const
2385 return const_cast<BufferView *>(this)->textMetrics(t);
2389 TextMetrics & BufferView::textMetrics(Text const * t)
2392 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
2393 if (tmc_it == d->text_metrics_.end()) {
2394 tmc_it = d->text_metrics_.insert(
2395 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
2397 return tmc_it->second;
2401 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2404 return textMetrics(t).parMetrics(pit);
2408 int BufferView::workHeight() const
2414 void BufferView::setCursor(DocIterator const & dit)
2417 size_t const n = dit.depth();
2418 for (size_t i = 0; i < n; ++i)
2419 dit[i].inset().edit(d->cursor_, true);
2421 d->cursor_.setCursor(dit);
2422 d->cursor_.setSelection(false);
2424 // It seems on general grounds as if this is probably needed, but
2425 // it is not yet clear.
2426 // See bug #7394 and r38388.
2427 // d->cursor.resetAnchor();
2431 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2433 // Would be wrong to delete anything if we have a selection.
2434 if (cur.selection())
2437 bool need_anchor_change = false;
2438 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
2439 need_anchor_change);
2441 if (need_anchor_change)
2449 // we would rather not do this here, but it needs to be done before
2450 // the changed() signal is sent.
2451 buffer_.updateBuffer();
2453 buffer_.changed(true);
2458 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
2460 LASSERT(&cur.bv() == this, return false);
2463 // this event will clear selection so we save selection for
2464 // persistent selection
2465 cap::saveSelection(cursor());
2467 d->cursor_.macroModeClose();
2468 // If a macro has been finalized, the cursor might have been broken
2471 // Has the cursor just left the inset?
2472 bool const leftinset = (&d->cursor_.inset() != &cur.inset());
2474 d->cursor_.fixIfBroken();
2476 // FIXME: shift-mouse selection doesn't work well across insets.
2477 bool const do_selection =
2478 select && &d->cursor_.normalAnchor().inset() == &cur.inset();
2480 // do the dEPM magic if needed
2481 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2482 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2483 // the leftinset bool would not be necessary (badcursor instead).
2484 bool update = leftinset;
2485 if (!do_selection && d->cursor_.inTexted())
2486 update |= checkDepm(cur, d->cursor_);
2489 d->cursor_.resetAnchor();
2490 d->cursor_.setCursor(cur);
2491 d->cursor_.boundary(cur.boundary());
2493 d->cursor_.setSelection();
2495 d->cursor_.clearSelection();
2497 d->cursor_.finishUndo();
2498 d->cursor_.setCurrentFont();
2500 cur.forceBufferUpdate();
2505 void BufferView::putSelectionAt(DocIterator const & cur,
2506 int length, bool backwards)
2508 d->cursor_.clearSelection();
2514 d->cursor_.pos() += length;
2515 d->cursor_.setSelection(d->cursor_, -length);
2517 d->cursor_.setSelection(d->cursor_, length);
2522 bool BufferView::selectIfEmpty(DocIterator & cur)
2524 if ((cur.inTexted() && !cur.paragraph().empty())
2525 || (cur.inMathed() && !cur.cell().empty()))
2528 pit_type const beg_pit = cur.pit();
2530 // The paragraph associated to this item isn't
2531 // the first one, so it can be selected
2534 // We have to resort to select the space between the
2535 // end of this item and the begin of the next one
2539 // If it is the only item in the document,
2540 // nothing can be selected
2543 pit_type const end_pit = cur.pit();
2544 pos_type const end_pos = cur.pos();
2545 d->cursor_.clearSelection();
2547 d->cursor_.setCursor(cur);
2548 d->cursor_.pit() = beg_pit;
2549 d->cursor_.pos() = 0;
2550 d->cursor_.setSelection(false);
2551 d->cursor_.resetAnchor();
2552 d->cursor_.pit() = end_pit;
2553 d->cursor_.pos() = end_pos;
2554 d->cursor_.setSelection();
2559 Cursor & BufferView::cursor()
2565 Cursor const & BufferView::cursor() const
2571 pit_type BufferView::anchor_ref() const
2573 return d->anchor_pit_;
2577 bool BufferView::singleParUpdate()
2579 Text & buftext = buffer_.text();
2580 pit_type const bottom_pit = d->cursor_.bottom().pit();
2581 TextMetrics & tm = textMetrics(&buftext);
2582 int old_height = tm.parMetrics(bottom_pit).height();
2584 // make sure inline completion pointer is ok
2585 if (d->inlineCompletionPos_.fixIfBroken())
2586 d->inlineCompletionPos_ = DocIterator();
2588 // In Single Paragraph mode, rebreak only
2589 // the (main text, not inset!) paragraph containing the cursor.
2590 // (if this paragraph contains insets etc., rebreaking will
2591 // recursively descend)
2592 tm.redoParagraph(bottom_pit);
2593 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
2594 if (pm.height() != old_height)
2595 // Paragraph height has changed so we cannot proceed to
2596 // the singlePar optimisation.
2599 d->update_strategy_ = SingleParUpdate;
2601 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2602 << " y2: " << pm.position() + pm.descent()
2603 << " pit: " << bottom_pit
2604 << " singlepar: 1");
2609 void BufferView::updateMetrics()
2611 if (height_ == 0 || width_ == 0)
2614 Text & buftext = buffer_.text();
2615 pit_type const npit = int(buftext.paragraphs().size());
2617 // Clear out the position cache in case of full screen redraw,
2618 d->coord_cache_.clear();
2620 // Clear out paragraph metrics to avoid having invalid metrics
2621 // in the cache from paragraphs not relayouted below
2622 // The complete text metrics will be redone.
2623 d->text_metrics_.clear();
2625 TextMetrics & tm = textMetrics(&buftext);
2627 // make sure inline completion pointer is ok
2628 if (d->inlineCompletionPos_.fixIfBroken())
2629 d->inlineCompletionPos_ = DocIterator();
2631 if (d->anchor_pit_ >= npit)
2632 // The anchor pit must have been deleted...
2633 d->anchor_pit_ = npit - 1;
2635 // Rebreak anchor paragraph.
2636 tm.redoParagraph(d->anchor_pit_);
2637 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2640 if (d->anchor_pit_ == 0) {
2641 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2643 // Complete buffer visible? Then it's easy.
2644 if (scrollRange == 0)
2645 d->anchor_ypos_ = anchor_pm.ascent();
2647 // FIXME: Some clever handling needed to show
2648 // the _first_ paragraph up to the top if the cursor is
2649 // in the first line.
2651 anchor_pm.setPosition(d->anchor_ypos_);
2653 LYXERR(Debug::PAINTING, "metrics: "
2654 << " anchor pit = " << d->anchor_pit_
2655 << " anchor ypos = " << d->anchor_ypos_);
2657 // Redo paragraphs above anchor if necessary.
2658 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2659 // We are now just above the anchor paragraph.
2660 pit_type pit1 = d->anchor_pit_ - 1;
2661 for (; pit1 >= 0 && y1 >= 0; --pit1) {
2662 tm.redoParagraph(pit1);
2663 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2665 // Save the paragraph position in the cache.
2670 // Redo paragraphs below the anchor if necessary.
2671 int y2 = d->anchor_ypos_ + anchor_pm.descent();
2672 // We are now just below the anchor paragraph.
2673 pit_type pit2 = d->anchor_pit_ + 1;
2674 for (; pit2 < npit && y2 <= height_; ++pit2) {
2675 tm.redoParagraph(pit2);
2676 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2678 // Save the paragraph position in the cache.
2683 LYXERR(Debug::PAINTING, "Metrics: "
2684 << " anchor pit = " << d->anchor_pit_
2685 << " anchor ypos = " << d->anchor_ypos_
2688 << " pit1 = " << pit1
2689 << " pit2 = " << pit2);
2691 d->update_strategy_ = FullScreenUpdate;
2693 if (lyxerr.debugging(Debug::WORKAREA)) {
2694 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2695 d->coord_cache_.dump();
2700 void BufferView::insertLyXFile(FileName const & fname)
2702 LASSERT(d->cursor_.inTexted(), return);
2704 // Get absolute path of file and add ".lyx"
2705 // to the filename if necessary
2706 FileName filename = fileSearch(string(), fname.absFileName(), "lyx");
2708 docstring const disp_fn = makeDisplayPath(filename.absFileName());
2709 // emit message signal.
2710 message(bformat(_("Inserting document %1$s..."), disp_fn));
2713 Buffer buf(filename.absFileName(), false);
2714 if (buf.loadLyXFile() == Buffer::ReadSuccess) {
2715 ErrorList & el = buffer_.errorList("Parse");
2716 // Copy the inserted document error list into the current buffer one.
2717 el = buf.errorList("Parse");
2718 buffer_.undo().recordUndo(d->cursor_);
2719 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2720 buf.params().documentClassPtr(), el);
2721 res = _("Document %1$s inserted.");
2723 res = _("Could not insert document %1$s");
2726 buffer_.changed(true);
2727 // emit message signal.
2728 message(bformat(res, disp_fn));
2732 Point BufferView::coordOffset(DocIterator const & dit) const
2738 // Addup contribution of nested insets, from inside to outside,
2739 // keeping the outer paragraph for a special handling below
2740 for (size_t i = dit.depth() - 1; i >= 1; --i) {
2741 CursorSlice const & sl = dit[i];
2745 // get relative position inside sl.inset()
2746 sl.inset().cursorPos(*this, sl, dit.boundary() && (i + 1 == dit.depth()), xx, yy);
2748 // Make relative position inside of the edited inset relative to sl.inset()
2752 // In case of an RTL inset, the edited inset will be positioned to the left
2755 bool boundary_i = dit.boundary() && i + 1 == dit.depth();
2756 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2761 // remember width for the case that sl.inset() is positioned in an RTL inset
2762 if (i && dit[i - 1].text()) {
2763 // If this Inset is inside a Text Inset, retrieve the Dimension
2764 // from the containing text instead of using Inset::dimension() which
2765 // might not be implemented.
2766 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2767 // elimination of Inset::dim_ cache. This coordOffset() method needs
2768 // to be rewritten in light of the new design.
2769 Dimension const & dim = parMetrics(dit[i - 1].text(),
2770 dit[i - 1].pit()).insetDimension(&sl.inset());
2773 Dimension const dim = sl.inset().dimension(*this);
2777 //lyxerr << "Cursor::getPos, i: "
2778 // << i << " x: " << xx << " y: " << y << endl;
2781 // Add contribution of initial rows of outermost paragraph
2782 CursorSlice const & sl = dit[0];
2783 TextMetrics const & tm = textMetrics(sl.text());
2784 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2786 LBUFERR(!pm.rows().empty());
2787 y -= pm.rows()[0].ascent();
2789 // FIXME: document this mess
2791 if (sl.pos() > 0 && dit.depth() == 1) {
2793 if (pos && dit.boundary())
2795 // lyxerr << "coordOffset: boundary:" << dit.boundary() << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2796 rend = pm.pos2row(pos);
2798 rend = pm.pos2row(sl.pos());
2800 size_t rend = pm.pos2row(sl.pos());
2802 for (size_t rit = 0; rit != rend; ++rit)
2803 y += pm.rows()[rit].height();
2804 y += pm.rows()[rend].ascent();
2806 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2808 // Make relative position from the nested inset now bufferview absolute.
2809 int xx = bottom_tm.cursorX(dit.bottom(), dit.boundary() && dit.depth() == 1);
2812 // In the RTL case place the nested inset at the left of the cursor in
2813 // the outer paragraph
2814 bool boundary_1 = dit.boundary() && 1 == dit.depth();
2815 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2823 Point BufferView::getPos(DocIterator const & dit) const
2825 if (!paragraphVisible(dit))
2826 return Point(-1, -1);
2828 CursorSlice const & bot = dit.bottom();
2829 TextMetrics const & tm = textMetrics(bot.text());
2831 // offset from outer paragraph
2832 Point p = coordOffset(dit);
2833 p.y_ += tm.parMetrics(bot.pit()).position();
2838 bool BufferView::paragraphVisible(DocIterator const & dit) const
2840 CursorSlice const & bot = dit.bottom();
2841 TextMetrics const & tm = textMetrics(bot.text());
2843 return tm.contains(bot.pit());
2847 void BufferView::cursorPosAndHeight(Point & p, int & h) const
2849 Cursor const & cur = cursor();
2850 Font const font = cur.getFont();
2851 frontend::FontMetrics const & fm = theFontMetrics(font);
2852 int const asc = fm.maxAscent();
2853 int const des = fm.maxDescent();
2860 bool BufferView::cursorInView(Point const & p, int h) const
2862 Cursor const & cur = cursor();
2863 // does the cursor touch the screen ?
2864 if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
2870 int BufferView::horizScrollOffset() const
2872 return d->horiz_scroll_offset_;
2876 CursorSlice const & BufferView::currentRowSlice() const
2878 return d->current_row_slice_;
2882 CursorSlice const & BufferView::lastRowSlice() const
2884 return d->last_row_slice_;
2888 void BufferView::setCurrentRowSlice(CursorSlice const & rowSlice)
2890 // nothing to do if the cursor was already on this row
2891 if (d->current_row_slice_ == rowSlice) {
2892 d->last_row_slice_ = CursorSlice();
2896 // if the (previous) current row was scrolled, we have to
2897 // remember it in order to repaint it next time.
2898 if (d->horiz_scroll_offset_ != 0)
2899 d->last_row_slice_ = d->current_row_slice_;
2901 d->last_row_slice_ = CursorSlice();
2903 // Since we changed row, the scroll offset is not valid anymore
2904 d->horiz_scroll_offset_ = 0;
2905 d->current_row_slice_ = rowSlice;
2909 void BufferView::checkCursorScrollOffset(PainterInfo & pi)
2911 CursorSlice rowSlice = d->cursor_.bottom();
2912 TextMetrics const & tm = textMetrics(rowSlice.text());
2914 // Stop if metrics have not been computed yet, since it means
2915 // that there is nothing to do.
2916 if (!tm.contains(rowSlice.pit()))
2918 ParagraphMetrics const & pm = tm.parMetrics(rowSlice.pit());
2919 Row const & row = pm.getRow(rowSlice.pos(),
2920 d->cursor_.boundary()
2921 && rowSlice == d->cursor_.top());
2922 rowSlice.pos() = row.pos();
2924 // Set the row on which the cursor lives.
2925 setCurrentRowSlice(rowSlice);
2927 // Force the recomputation of inset positions
2928 bool const drawing = pi.pain.isDrawingEnabled();
2929 pi.pain.setDrawingEnabled(false);
2930 // No need to care about vertical position.
2931 RowPainter rp(pi, buffer().text(), d->cursor_.bottom().pit(), row, 0, 0);
2933 pi.pain.setDrawingEnabled(drawing);
2935 // Current x position of the cursor in pixels
2936 int const cur_x = getPos(d->cursor_).x_;
2938 // Horizontal scroll offset of the cursor row in pixels
2939 int offset = d->horiz_scroll_offset_;
2940 int const MARGIN = 10;
2941 if (cur_x < offset + MARGIN) {
2943 offset = cur_x - MARGIN;
2944 } else if (cur_x > offset + workWidth() - MARGIN) {
2946 offset = cur_x - workWidth() + MARGIN;
2947 } else if(offset > 0
2948 && row.width() - offset < workWidth()){
2949 offset = row.width() - workWidth();
2952 if (offset != d->horiz_scroll_offset_)
2953 LYXERR0("Offset is now " << offset);
2955 if (d->update_strategy_ == NoScreenUpdate
2956 && (offset != d->horiz_scroll_offset_
2957 || !d->last_row_slice_.empty())) {
2958 // FIXME: if one uses SingleParUpdate, then home/end
2959 // will not work on long rows. Why?
2960 d->update_strategy_ = FullScreenUpdate;//DecorationUpdate;
2963 d->horiz_scroll_offset_ = offset;
2967 void BufferView::draw(frontend::Painter & pain)
2969 if (height_ == 0 || width_ == 0)
2971 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2973 Text & text = buffer_.text();
2974 TextMetrics const & tm = d->text_metrics_[&text];
2975 int const y = tm.first().second->position();
2976 PainterInfo pi(this, pain);
2978 // Check whether the row where the cursor lives needs to be scrolled.
2979 // Update the drawing strategy if needed.
2980 checkCursorScrollOffset(pi);
2982 switch (d->update_strategy_) {
2984 case NoScreenUpdate:
2985 // If no screen painting is actually needed, only some the different
2986 // coordinates of insets and paragraphs needs to be updated.
2987 pi.full_repaint = true;
2988 pi.pain.setDrawingEnabled(false);
2992 case SingleParUpdate:
2993 pi.full_repaint = false;
2994 // In general, only the current row of the outermost paragraph
2995 // will be redrawn. Particular cases where selection spans
2996 // multiple paragraph are correctly detected in TextMetrics.
3000 case DecorationUpdate:
3001 // FIXME: We should also distinguish DecorationUpdate to avoid text
3002 // drawing if possible. This is not possible to do easily right now
3003 // because of the single backing pixmap.
3005 case FullScreenUpdate:
3006 // The whole screen, including insets, will be refreshed.
3007 pi.full_repaint = true;
3009 // Clear background.
3010 pain.fillRectangle(0, 0, width_, height_,
3011 pi.backgroundColor(&buffer_.inset()));
3016 // and possibly grey out below
3017 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3018 int const y2 = lastpm.second->position() + lastpm.second->descent();
3021 Color color = buffer().isInternal()
3022 ? Color_background : Color_bottomarea;
3023 pain.fillRectangle(0, y2, width_, height_ - y2, color);
3027 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
3029 // The scrollbar needs an update.
3032 // Normalize anchor for next time
3033 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
3034 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3035 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
3036 ParagraphMetrics const & pm = tm.parMetrics(pit);
3037 if (pm.position() + pm.descent() > 0) {
3038 d->anchor_pit_ = pit;
3039 d->anchor_ypos_ = pm.position();
3043 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
3044 << " anchor ypos = " << d->anchor_ypos_);
3048 void BufferView::message(docstring const & msg)
3051 d->gui_->message(msg);
3055 void BufferView::showDialog(string const & name)
3058 d->gui_->showDialog(name, string());
3062 void BufferView::showDialog(string const & name,
3063 string const & data, Inset * inset)
3066 d->gui_->showDialog(name, data, inset);
3070 void BufferView::updateDialog(string const & name, string const & data)
3073 d->gui_->updateDialog(name, data);
3077 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
3083 // FIXME: Move this out of BufferView again
3084 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
3086 if (!fname.isReadableFile()) {
3087 docstring const error = from_ascii(strerror(errno));
3088 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3089 docstring const text =
3090 bformat(_("Could not read the specified document\n"
3091 "%1$s\ndue to the error: %2$s"), file, error);
3092 Alert::error(_("Could not read file"), text);
3096 if (!fname.isReadableFile()) {
3097 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3098 docstring const text =
3099 bformat(_("%1$s\n is not readable."), file);
3100 Alert::error(_("Could not open file"), text);
3104 // FIXME UNICODE: We don't know the encoding of the file
3105 docstring file_content = fname.fileContents("UTF-8");
3106 if (file_content.empty()) {
3107 Alert::error(_("Reading not UTF-8 encoded file"),
3108 _("The file is not UTF-8 encoded.\n"
3109 "It will be read as local 8Bit-encoded.\n"
3110 "If this does not give the correct result\n"
3111 "then please change the encoding of the file\n"
3112 "to UTF-8 with a program other than LyX.\n"));
3113 file_content = fname.fileContents("local8bit");
3116 return normalize_c(file_content);
3120 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
3122 docstring const tmpstr = contentsOfPlaintextFile(f);
3127 Cursor & cur = cursor();
3128 cap::replaceSelection(cur);
3129 buffer_.undo().recordUndo(cur);
3131 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
3133 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
3135 buffer_.changed(true);
3139 docstring const & BufferView::inlineCompletion() const
3141 return d->inlineCompletion_;
3145 size_t const & BufferView::inlineCompletionUniqueChars() const
3147 return d->inlineCompletionUniqueChars_;
3151 DocIterator const & BufferView::inlineCompletionPos() const
3153 return d->inlineCompletionPos_;
3157 void BufferView::resetInlineCompletionPos()
3159 d->inlineCompletionPos_ = DocIterator();
3163 bool samePar(DocIterator const & a, DocIterator const & b)
3165 if (a.empty() && b.empty())
3167 if (a.empty() || b.empty())
3169 if (a.depth() != b.depth())
3171 return &a.innerParagraph() == &b.innerParagraph();
3175 void BufferView::setInlineCompletion(Cursor const & cur, DocIterator const & pos,
3176 docstring const & completion, size_t uniqueChars)
3178 uniqueChars = min(completion.size(), uniqueChars);
3179 bool changed = d->inlineCompletion_ != completion
3180 || d->inlineCompletionUniqueChars_ != uniqueChars;
3181 bool singlePar = true;
3182 d->inlineCompletion_ = completion;
3183 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
3185 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
3188 DocIterator const & old = d->inlineCompletionPos_;
3190 //lyxerr << "inlineCompletionPos changed" << std::endl;
3191 // old or pos are in another paragraph?
3192 if ((!samePar(cur, pos) && !pos.empty())
3193 || (!samePar(cur, old) && !old.empty())) {
3195 //lyxerr << "different paragraph" << std::endl;
3197 d->inlineCompletionPos_ = pos;
3202 if (singlePar && !(cur.result().screenUpdate() & Update::Force))
3203 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
3205 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::Force);
3210 bool BufferView::clickableInset() const
3212 return d->clickable_inset_;