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"
55 #include "WordLangTuple.h"
57 #include "insets/InsetBibtex.h"
58 #include "insets/InsetCommand.h" // ChangeRefs
59 #include "insets/InsetExternal.h"
60 #include "insets/InsetGraphics.h"
61 #include "insets/InsetNote.h"
62 #include "insets/InsetRef.h"
63 #include "insets/InsetText.h"
65 #include "frontends/alert.h"
66 #include "frontends/Application.h"
67 #include "frontends/Delegates.h"
68 #include "frontends/FontMetrics.h"
69 #include "frontends/Painter.h"
70 #include "frontends/Selection.h"
72 #include "graphics/Previews.h"
74 #include "support/convert.h"
75 #include "support/debug.h"
76 #include "support/ExceptionMessage.h"
77 #include "support/filetools.h"
78 #include "support/gettext.h"
79 #include "support/lstrings.h"
80 #include "support/Package.h"
81 #include "support/types.h"
91 using namespace lyx::support;
95 namespace Alert = frontend::Alert;
99 /// Return an inset of this class if it exists at the current cursor position
101 T * getInsetByCode(Cursor const & cur, InsetCode code)
103 DocIterator it = cur;
104 Inset * inset = it.nextInset();
105 if (inset && inset->lyxCode() == code)
106 return static_cast<T*>(inset);
110 /// Note that comparing contents can only be used for InsetCommand
111 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
112 docstring const & contents)
114 DocIterator tmpdit = dit;
117 Inset const * inset = tmpdit.nextInset();
119 bool const valid_code = std::find(codes.begin(), codes.end(),
120 inset->lyxCode()) != codes.end();
121 InsetCommand const * ic = inset->asInsetCommand();
122 bool const same_or_no_contents = contents.empty()
123 || (ic && (ic->getFirstNonOptParam() == contents));
125 if (valid_code && same_or_no_contents) {
130 tmpdit.forwardInset();
137 /// Looks for next inset with one of the given codes.
138 /// Note that same_content can only be used for InsetCommand
139 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
143 DocIterator tmpdit = dit;
144 tmpdit.forwardInset();
148 Inset const * inset = tmpdit.nextInset();
149 if (same_content && inset) {
150 InsetCommand const * ic = inset->asInsetCommand();
152 bool const valid_code = std::find(codes.begin(), codes.end(),
153 ic->lyxCode()) != codes.end();
155 contents = ic->getFirstNonOptParam();
159 if (!findNextInset(tmpdit, codes, contents)) {
160 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
161 Inset * inset = &tmpdit.bottom().inset();
162 tmpdit = doc_iterator_begin(&inset->buffer(), inset);
163 if (!findNextInset(tmpdit, codes, contents))
175 /// Looks for next inset with the given code
176 void findInset(DocIterator & dit, InsetCode code, bool same_content)
178 findInset(dit, vector<InsetCode>(1, code), same_content);
182 /// Moves cursor to the next inset with one of the given codes.
183 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
186 Cursor tmpcur = bv->cursor();
187 if (!findInset(tmpcur, codes, same_content)) {
188 bv->cursor().message(_("No more insets"));
192 tmpcur.clearSelection();
193 bv->setCursor(tmpcur);
198 /// Moves cursor to the next inset with given code.
199 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
201 gotoInset(bv, vector<InsetCode>(1, code), same_content);
205 /// A map from a Text to the associated text metrics
206 typedef map<Text const *, TextMetrics> TextMetricsCache;
208 enum ScreenUpdateStrategy {
218 /////////////////////////////////////////////////////////////////////
222 /////////////////////////////////////////////////////////////////////
224 struct BufferView::Private
226 Private(BufferView & bv): wh_(0), cursor_(bv),
227 anchor_pit_(0), anchor_ypos_(0),
228 inlineCompletionUniqueChars_(0),
229 last_inset_(0), clickable_inset_(false),
230 mouse_position_cache_(),
231 bookmark_edit_position_(-1), gui_(0)
235 ScrollbarParameters scrollbarParameters_;
237 ScreenUpdateStrategy update_strategy_;
239 CoordCache coord_cache_;
241 /// Estimated average par height for scrollbar.
243 /// this is used to handle XSelection events in the right manner.
252 pit_type anchor_pit_;
256 vector<int> par_height_;
259 DocIterator inlineCompletionPos_;
261 docstring inlineCompletion_;
263 size_t inlineCompletionUniqueChars_;
265 /// keyboard mapping object.
268 /// last visited inset.
269 /** kept to send setMouseHover(false).
270 * Not owned, so don't delete.
272 Inset const * last_inset_;
273 /// are we hovering something that we can click
274 bool clickable_inset_;
276 /// position of the mouse at the time of the last mouse move
277 /// This is used to update the hovering status of inset in
278 /// cases where the buffer is scrolled, but the mouse didn't move.
279 Point mouse_position_cache_;
281 // cache for id of the paragraph which was edited the last time
282 int bookmark_edit_position_;
284 mutable TextMetricsCache text_metrics_;
287 /** Not owned, so don't delete.
289 frontend::GuiBufferViewDelegate * gui_;
291 /// Cache for Find Next
292 FuncRequest search_request_cache_;
295 map<string, Inset *> edited_insets_;
299 BufferView::BufferView(Buffer & buf)
300 : width_(0), height_(0), full_screen_(false), buffer_(buf),
301 d(new Private(*this))
303 d->xsel_cache_.set = false;
304 d->intl_.initKeyMapper(lyxrc.use_kbmap);
306 d->cursor_.setBuffer(&buf);
307 d->cursor_.push(buffer_.inset());
308 d->cursor_.resetAnchor();
309 d->cursor_.setCurrentFont();
311 buffer_.updatePreviews();
315 BufferView::~BufferView()
317 // current buffer is going to be switched-off, save cursor pos
318 // Ideally, the whole cursor stack should be saved, but session
319 // currently can only handle bottom (whole document) level pit and pos.
320 // That is to say, if a cursor is in a nested inset, it will be
321 // restore to the left of the top level inset.
322 LastFilePosSection::FilePos fp;
323 fp.pit = d->cursor_.bottom().pit();
324 fp.pos = d->cursor_.bottom().pos();
325 theSession().lastFilePos().save(buffer_.fileName(), fp);
328 d->last_inset_->setMouseHover(this, false);
334 int BufferView::rightMargin() const
336 // The additional test for the case the outliner is opened.
338 !lyxrc.full_screen_limit ||
339 width_ < lyxrc.full_screen_width + 20)
342 return (width_ - lyxrc.full_screen_width) / 2;
346 int BufferView::leftMargin() const
348 return rightMargin();
352 bool BufferView::isTopScreen() const
354 return d->scrollbarParameters_.position == d->scrollbarParameters_.min;
358 bool BufferView::isBottomScreen() const
360 return d->scrollbarParameters_.position == d->scrollbarParameters_.max;
364 Intl & BufferView::getIntl()
370 Intl const & BufferView::getIntl() const
376 CoordCache & BufferView::coordCache()
378 return d->coord_cache_;
382 CoordCache const & BufferView::coordCache() const
384 return d->coord_cache_;
388 Buffer & BufferView::buffer()
394 Buffer const & BufferView::buffer() const
400 bool BufferView::fitCursor()
402 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
403 frontend::FontMetrics const & fm =
404 theFontMetrics(d->cursor_.getFont().fontInfo());
405 int const asc = fm.maxAscent();
406 int const des = fm.maxDescent();
407 Point const p = getPos(d->cursor_);
408 if (p.y_ - asc >= 0 && p.y_ + des < height_)
415 void BufferView::processUpdateFlags(Update::flags flags)
417 // This is close to a hot-path.
418 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
419 << "[fitcursor = " << (flags & Update::FitCursor)
420 << ", forceupdate = " << (flags & Update::Force)
421 << ", singlepar = " << (flags & Update::SinglePar)
422 << "] buffer: " << &buffer_);
424 // FIXME Does this really need doing here? It's done in updateBuffer, and
425 // if the Buffer doesn't need updating, then do the macros?
426 buffer_.updateMacros();
428 // Now do the first drawing step if needed. This consists on updating
429 // the CoordCache in updateMetrics().
430 // The second drawing step is done in WorkArea::redraw() if needed.
432 // Case when no explicit update is requested.
434 // no need to redraw anything.
435 d->update_strategy_ = NoScreenUpdate;
439 if (flags == Update::Decoration) {
440 d->update_strategy_ = DecorationUpdate;
441 buffer_.changed(false);
445 if (flags == Update::FitCursor
446 || flags == (Update::Decoration | Update::FitCursor)) {
447 // tell the frontend to update the screen if needed.
452 if (flags & Update::Decoration) {
453 d->update_strategy_ = DecorationUpdate;
454 buffer_.changed(false);
457 // no screen update is needed.
458 d->update_strategy_ = NoScreenUpdate;
462 bool const full_metrics = flags & Update::Force || !singleParUpdate();
465 // We have to update the full screen metrics.
468 if (!(flags & Update::FitCursor)) {
469 // Nothing to do anymore. Trigger a redraw and return
470 buffer_.changed(false);
474 // updateMetrics() does not update paragraph position
475 // This is done at draw() time. So we need a redraw!
476 buffer_.changed(false);
479 // The cursor is off screen so ensure it is visible.
484 updateHoveredInset();
488 void BufferView::updateScrollbar()
490 if (height_ == 0 && width_ == 0)
493 // We prefer fixed size line scrolling.
494 d->scrollbarParameters_.single_step = defaultRowHeight();
495 // We prefer full screen page scrolling.
496 d->scrollbarParameters_.page_step = height_;
498 Text & t = buffer_.text();
499 TextMetrics & tm = d->text_metrics_[&t];
501 LYXERR(Debug::GUI, " Updating scrollbar: height: "
502 << t.paragraphs().size()
503 << " curr par: " << d->cursor_.bottom().pit()
504 << " default height " << defaultRowHeight());
506 size_t const parsize = t.paragraphs().size();
507 if (d->par_height_.size() != parsize) {
508 d->par_height_.clear();
509 // FIXME: We assume a default paragraph height of 2 rows. This
510 // should probably be pondered with the screen width.
511 d->par_height_.resize(parsize, defaultRowHeight() * 2);
514 // Look at paragraph heights on-screen
515 pair<pit_type, ParagraphMetrics const *> first = tm.first();
516 pair<pit_type, ParagraphMetrics const *> last = tm.last();
517 for (pit_type pit = first.first; pit <= last.first; ++pit) {
518 d->par_height_[pit] = tm.parMetrics(pit).height();
519 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
520 << d->par_height_[pit]);
523 int top_pos = first.second->position() - first.second->ascent();
524 int bottom_pos = last.second->position() + last.second->descent();
525 bool first_visible = first.first == 0 && top_pos >= 0;
526 bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
527 if (first_visible && last_visible) {
528 d->scrollbarParameters_.min = 0;
529 d->scrollbarParameters_.max = 0;
533 d->scrollbarParameters_.min = top_pos;
534 for (size_t i = 0; i != size_t(first.first); ++i)
535 d->scrollbarParameters_.min -= d->par_height_[i];
536 d->scrollbarParameters_.max = bottom_pos;
537 for (size_t i = last.first + 1; i != parsize; ++i)
538 d->scrollbarParameters_.max += d->par_height_[i];
540 d->scrollbarParameters_.position = 0;
541 // The reference is the top position so we remove one page.
542 if (lyxrc.scroll_below_document)
543 d->scrollbarParameters_.max -= minVisiblePart();
545 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
549 ScrollbarParameters const & BufferView::scrollbarParameters() const
551 return d->scrollbarParameters_;
555 docstring BufferView::toolTip(int x, int y) const
557 // Get inset under mouse, if there is one.
558 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
560 // No inset, no tooltip...
562 return covering_inset->toolTip(*this, x, y);
566 docstring BufferView::contextMenu(int x, int y) const
568 //If there is a selection, return the containing inset menu
569 if (d->cursor_.selection())
570 return d->cursor_.inset().contextMenu(*this, x, y);
572 // Get inset under mouse, if there is one.
573 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
575 return covering_inset->contextMenu(*this, x, y);
577 return buffer_.inset().contextMenu(*this, x, y);
581 void BufferView::scrollDocView(int value, bool update)
583 int const offset = value - d->scrollbarParameters_.position;
585 // No scrolling at all? No need to redraw anything
589 // If the offset is less than 2 screen height, prefer to scroll instead.
590 if (abs(offset) <= 2 * height_) {
591 d->anchor_ypos_ -= offset;
592 buffer_.changed(true);
593 updateHoveredInset();
597 // cut off at the top
598 if (value <= d->scrollbarParameters_.min) {
599 DocIterator dit = doc_iterator_begin(&buffer_);
600 showCursor(dit, false, update);
601 LYXERR(Debug::SCROLLING, "scroll to top");
605 // cut off at the bottom
606 if (value >= d->scrollbarParameters_.max) {
607 DocIterator dit = doc_iterator_end(&buffer_);
609 showCursor(dit, false, update);
610 LYXERR(Debug::SCROLLING, "scroll to bottom");
614 // find paragraph at target position
615 int par_pos = d->scrollbarParameters_.min;
617 for (; i != int(d->par_height_.size()); ++i) {
618 par_pos += d->par_height_[i];
619 if (par_pos >= value)
623 if (par_pos < value) {
624 // It seems we didn't find the correct pit so stay on the safe side and
626 LYXERR0("scrolling position not found!");
627 scrollDocView(d->scrollbarParameters_.max, update);
631 DocIterator dit = doc_iterator_begin(&buffer_);
633 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
634 showCursor(dit, false, update);
638 // FIXME: this method is not working well.
639 void BufferView::setCursorFromScrollbar()
641 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
643 int const height = 2 * defaultRowHeight();
644 int const first = height;
645 int const last = height_ - height;
647 Cursor const & oldcur = d->cursor_;
649 switch (cursorStatus(oldcur)) {
657 int const y = getPos(oldcur).y_;
658 newy = min(last, max(y, first));
662 // We reset the cursor because cursorStatus() does not
663 // work when the cursor is within mathed.
666 tm.setCursorFromCoordinates(cur, 0, newy);
668 // update the bufferview cursor and notify insets
669 // FIXME: Care about the d->cursor_ flags to redraw if needed
670 Cursor old = d->cursor_;
672 bool badcursor = notifyCursorLeavesOrEnters(old, d->cursor_);
674 d->cursor_.fixIfBroken();
678 Change const BufferView::getCurrentChange() const
680 if (!d->cursor_.selection())
681 return Change(Change::UNCHANGED);
683 DocIterator dit = d->cursor_.selectionBegin();
684 return dit.paragraph().lookupChange(dit.pos());
688 // this could be used elsewhere as well?
689 // FIXME: This does not work within mathed!
690 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
692 Point const p = getPos(dit);
695 if (p.y_ > workHeight())
701 void BufferView::bookmarkEditPosition()
703 d->cursor_.markEditPosition();
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 // If the top part of the row falls of the screen, we scroll
889 // up to align the top of the row with the top of the screen.
890 else if (ypos - row_dim.ascent() < 0)
891 scrolled = scrollUp(-ypos + row_dim.ascent());
893 // If the bottom of the row falls of the screen, we scroll down.
894 // However, we have to be careful not to scroll that much that
895 // the top falls of the screen.
896 else if (ypos + row_dim.descent() > height_) {
897 int ynew = height_ - row_dim.descent();
898 if (ynew < row_dim.ascent())
899 ynew = row_dim.ascent();
900 int const scroll = ypos - ynew;
901 scrolled = scrollDown(scroll);
904 // else, nothing to do, the cursor is already visible so we just return.
905 return scrolled != 0;
908 // fix inline completion position
909 if (d->inlineCompletionPos_.fixIfBroken())
910 d->inlineCompletionPos_ = DocIterator();
912 tm.redoParagraph(bot_pit);
913 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
914 int offset = coordOffset(dit).y_;
916 d->anchor_pit_ = bot_pit;
917 CursorSlice const & cs = dit.innerTextSlice();
918 Dimension const & row_dim =
919 pm.getRow(cs.pos(), dit.boundary()).dimension();
922 d->anchor_ypos_ = height_/2;
923 else if (d->anchor_pit_ == 0)
924 d->anchor_ypos_ = offset + pm.ascent();
925 else if (d->anchor_pit_ == max_pit)
926 d->anchor_ypos_ = height_ - offset - row_dim.descent();
927 else if (offset > height_)
928 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
930 d->anchor_ypos_ = defaultRowHeight() * 2;
936 void BufferView::updateDocumentClass(DocumentClass const * const olddc)
938 message(_("Converting document to new document class..."));
940 StableDocIterator backcur(d->cursor_);
941 ErrorList & el = buffer_.errorList("Class Switch");
942 cap::switchBetweenClasses(
943 olddc, buffer_.params().documentClassPtr(),
944 static_cast<InsetText &>(buffer_.inset()), el);
946 setCursor(backcur.asDocIterator(&buffer_));
948 buffer_.errors("Class Switch");
951 /** Return the change status at cursor position, taking in account the
952 * status at each level of the document iterator (a table in a deleted
953 * footnote is deleted).
954 * When \param outer is true, the top slice is not looked at.
956 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
958 size_t const depth = dit.depth() - (outer ? 1 : 0);
960 for (size_t i = 0 ; i < depth ; ++i) {
961 CursorSlice const & slice = dit[i];
962 if (!slice.inset().inMathed()
963 && slice.pos() < slice.paragraph().size()) {
964 Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
965 if (ch != Change::UNCHANGED)
969 return Change::UNCHANGED;
973 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
975 FuncCode const act = cmd.action();
977 // Can we use a readonly buffer?
978 if (buffer_.isReadonly()
979 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
980 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
981 flag.message(from_utf8(N_("Document is read-only")));
982 flag.setEnabled(false);
986 // Are we in a DELETED change-tracking region?
987 if (lookupChangeType(d->cursor_, true) == Change::DELETED
988 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
989 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
990 flag.message(from_utf8(N_("This portion of the document is deleted.")));
991 flag.setEnabled(false);
995 Cursor & cur = d->cursor_;
997 if (cur.getStatus(cmd, flag))
1002 // FIXME: This is a bit problematic because we don't check if this is
1003 // a document BufferView or not for these LFUNs. We probably have to
1004 // dispatch both to currentBufferView() and, if that fails,
1005 // to documentBufferView(); same as we do now for current Buffer and
1006 // document Buffer. Ideally those LFUN should go to Buffer as they
1007 // operate on the full Buffer and the cursor is only needed either for
1008 // an Undo record or to restore a cursor position. But we don't know
1009 // how to do that inside Buffer of course.
1010 case LFUN_BUFFER_PARAMS_APPLY:
1011 case LFUN_LAYOUT_MODULES_CLEAR:
1012 case LFUN_LAYOUT_MODULE_ADD:
1013 case LFUN_LAYOUT_RELOAD:
1014 case LFUN_TEXTCLASS_APPLY:
1015 case LFUN_TEXTCLASS_LOAD:
1016 flag.setEnabled(!buffer_.isReadonly());
1020 // We do not use the LyXAction flag for readonly because Undo sets the
1021 // buffer clean/dirty status by itself.
1022 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasUndoStack());
1025 // We do not use the LyXAction flag for readonly because Redo sets the
1026 // buffer clean/dirty status by itself.
1027 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasRedoStack());
1029 case LFUN_FILE_INSERT:
1030 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1031 case LFUN_FILE_INSERT_PLAINTEXT:
1032 case LFUN_BOOKMARK_SAVE:
1033 // FIXME: Actually, these LFUNS should be moved to Text
1034 flag.setEnabled(cur.inTexted());
1037 case LFUN_FONT_STATE:
1038 case LFUN_LABEL_INSERT:
1039 case LFUN_INFO_INSERT:
1040 case LFUN_PARAGRAPH_GOTO:
1041 case LFUN_NOTE_NEXT:
1042 case LFUN_REFERENCE_NEXT:
1043 case LFUN_WORD_FIND:
1044 case LFUN_WORD_FIND_FORWARD:
1045 case LFUN_WORD_FIND_BACKWARD:
1046 case LFUN_WORD_FINDADV:
1047 case LFUN_WORD_REPLACE:
1050 case LFUN_MARK_TOGGLE:
1051 case LFUN_SCREEN_RECENTER:
1052 case LFUN_SCREEN_SHOW_CURSOR:
1053 case LFUN_BIBTEX_DATABASE_ADD:
1054 case LFUN_BIBTEX_DATABASE_DEL:
1055 case LFUN_STATISTICS:
1056 case LFUN_BRANCH_ADD_INSERT:
1057 case LFUN_KEYMAP_OFF:
1058 case LFUN_KEYMAP_PRIMARY:
1059 case LFUN_KEYMAP_SECONDARY:
1060 case LFUN_KEYMAP_TOGGLE:
1061 flag.setEnabled(true);
1064 case LFUN_LABEL_GOTO: {
1065 flag.setEnabled(!cmd.argument().empty()
1066 || getInsetByCode<InsetRef>(cur, REF_CODE));
1070 case LFUN_CHANGES_TRACK:
1071 flag.setEnabled(true);
1072 flag.setOnOff(buffer_.params().trackChanges);
1075 case LFUN_CHANGES_OUTPUT:
1076 flag.setEnabled(true);
1077 flag.setOnOff(buffer_.params().outputChanges);
1080 case LFUN_CHANGES_MERGE:
1081 case LFUN_CHANGE_NEXT:
1082 case LFUN_CHANGE_PREVIOUS:
1083 case LFUN_ALL_CHANGES_ACCEPT:
1084 case LFUN_ALL_CHANGES_REJECT:
1085 // TODO: context-sensitive enabling of LFUNs
1086 // In principle, these command should only be enabled if there
1087 // is a change in the document. However, without proper
1088 // optimizations, this will inevitably result in poor performance.
1089 flag.setEnabled(true);
1092 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
1093 flag.setOnOff(buffer_.params().compressed);
1097 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC: {
1098 flag.setOnOff(buffer_.params().output_sync);
1102 case LFUN_SCREEN_UP:
1103 case LFUN_SCREEN_DOWN:
1105 case LFUN_SCREEN_UP_SELECT:
1106 case LFUN_SCREEN_DOWN_SELECT:
1107 case LFUN_INSET_FORALL:
1108 flag.setEnabled(true);
1111 case LFUN_LAYOUT_TABULAR:
1112 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1116 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1119 case LFUN_LAYOUT_PARAGRAPH:
1120 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1123 case LFUN_DIALOG_SHOW_NEW_INSET:
1124 // FIXME: this is wrong, but I do not understand the
1126 if (cur.inset().lyxCode() == CAPTION_CODE)
1127 return cur.inset().getStatus(cur, cmd, flag);
1128 // FIXME we should consider passthru paragraphs too.
1129 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1132 case LFUN_CITATION_INSERT: {
1133 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1134 // FIXME: This could turn in a recursive hell.
1135 // Shouldn't we use Buffer::getStatus() instead?
1136 flag.setEnabled(lyx::getStatus(fr).enabled());
1139 case LFUN_INSET_APPLY: {
1140 string const name = cmd.getArg(0);
1141 Inset * inset = editedInset(name);
1143 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1144 if (!inset->getStatus(cur, fr, flag)) {
1145 // Every inset is supposed to handle this
1146 LASSERT(false, break);
1149 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1150 flag = lyx::getStatus(fr);
1163 Inset * BufferView::editedInset(string const & name) const
1165 map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1166 return it == d->edited_insets_.end() ? 0 : it->second;
1170 void BufferView::editInset(string const & name, Inset * inset)
1172 d->edited_insets_[name] = inset;
1176 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1178 //lyxerr << [ cmd = " << cmd << "]" << endl;
1180 // Make sure that the cached BufferView is correct.
1181 LYXERR(Debug::ACTION, " action[" << cmd.action() << ']'
1182 << " arg[" << to_utf8(cmd.argument()) << ']'
1183 << " x[" << cmd.x() << ']'
1184 << " y[" << cmd.y() << ']'
1185 << " button[" << cmd.button() << ']');
1187 string const argument = to_utf8(cmd.argument());
1188 Cursor & cur = d->cursor_;
1190 // Don't dispatch function that does not apply to internal buffers.
1191 if (buffer_.isInternal()
1192 && lyxaction.funcHasFlag(cmd.action(), LyXAction::NoInternal))
1195 // We'll set this back to false if need be.
1196 bool dispatched = true;
1197 buffer_.undo().beginUndoGroup();
1199 FuncCode const act = cmd.action();
1202 case LFUN_BUFFER_PARAMS_APPLY: {
1203 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1204 cur.recordUndoFullDocument();
1205 istringstream ss(to_utf8(cmd.argument()));
1208 int const unknown_tokens = buffer_.readHeader(lex);
1209 if (unknown_tokens != 0) {
1210 LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1211 << unknown_tokens << " unknown token"
1212 << (unknown_tokens == 1 ? "" : "s"));
1214 updateDocumentClass(oldClass);
1216 // We are most certainly here because of a change in the document
1217 // It is then better to make sure that all dialogs are in sync with
1218 // current document settings.
1219 dr.screenUpdate(Update::Force | Update::FitCursor);
1220 dr.forceBufferUpdate();
1224 case LFUN_LAYOUT_MODULES_CLEAR: {
1225 DocumentClass const * const oldClass =
1226 buffer_.params().documentClassPtr();
1227 cur.recordUndoFullDocument();
1228 buffer_.params().clearLayoutModules();
1229 buffer_.params().makeDocumentClass();
1230 updateDocumentClass(oldClass);
1231 dr.screenUpdate(Update::Force);
1232 dr.forceBufferUpdate();
1236 case LFUN_LAYOUT_MODULE_ADD: {
1237 BufferParams const & params = buffer_.params();
1238 if (!params.moduleCanBeAdded(argument)) {
1239 LYXERR0("Module `" << argument <<
1240 "' cannot be added due to failed requirements or "
1241 "conflicts with installed modules.");
1244 DocumentClass const * const oldClass = params.documentClassPtr();
1245 cur.recordUndoFullDocument();
1246 buffer_.params().addLayoutModule(argument);
1247 buffer_.params().makeDocumentClass();
1248 updateDocumentClass(oldClass);
1249 dr.screenUpdate(Update::Force);
1250 dr.forceBufferUpdate();
1254 case LFUN_TEXTCLASS_APPLY: {
1255 // since this shortcircuits, the second call is made only if
1257 bool const success =
1258 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1259 LayoutFileList::get().load(argument, buffer_.filePath());
1261 docstring s = bformat(_("The document class `%1$s' "
1262 "could not be loaded."), from_utf8(argument));
1263 frontend::Alert::error(_("Could not load class"), s);
1267 LayoutFile const * old_layout = buffer_.params().baseClass();
1268 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1270 if (old_layout == new_layout)
1274 // Save the old, possibly modular, layout for use in conversion.
1275 DocumentClass const * const oldDocClass =
1276 buffer_.params().documentClassPtr();
1277 cur.recordUndoFullDocument();
1278 buffer_.params().setBaseClass(argument);
1279 buffer_.params().makeDocumentClass();
1280 updateDocumentClass(oldDocClass);
1281 dr.screenUpdate(Update::Force);
1282 dr.forceBufferUpdate();
1286 case LFUN_TEXTCLASS_LOAD: {
1287 // since this shortcircuits, the second call is made only if
1289 bool const success =
1290 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1291 LayoutFileList::get().load(argument, buffer_.filePath());
1293 docstring s = bformat(_("The document class `%1$s' "
1294 "could not be loaded."), from_utf8(argument));
1295 frontend::Alert::error(_("Could not load class"), s);
1300 case LFUN_LAYOUT_RELOAD: {
1301 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1302 LayoutFileIndex bc = buffer_.params().baseClassID();
1303 LayoutFileList::get().reset(bc);
1304 buffer_.params().setBaseClass(bc);
1305 buffer_.params().makeDocumentClass();
1306 updateDocumentClass(oldClass);
1307 dr.screenUpdate(Update::Force);
1308 dr.forceBufferUpdate();
1313 dr.setMessage(_("Undo"));
1314 cur.clearSelection();
1315 if (!cur.textUndo())
1316 dr.setMessage(_("No further undo information"));
1318 dr.screenUpdate(Update::Force | Update::FitCursor);
1319 dr.forceBufferUpdate();
1323 dr.setMessage(_("Redo"));
1324 cur.clearSelection();
1325 if (!cur.textRedo())
1326 dr.setMessage(_("No further redo information"));
1328 dr.screenUpdate(Update::Force | Update::FitCursor);
1329 dr.forceBufferUpdate();
1332 case LFUN_FONT_STATE:
1333 dr.setMessage(cur.currentState());
1336 case LFUN_BOOKMARK_SAVE:
1337 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1340 case LFUN_LABEL_GOTO: {
1341 docstring label = cmd.argument();
1342 if (label.empty()) {
1344 getInsetByCode<InsetRef>(cur, REF_CODE);
1346 label = inset->getParam("reference");
1347 // persistent=false: use temp_bookmark
1351 if (!label.empty()) {
1353 // at the moment, this is redundant, since gotoLabel will
1354 // eventually call LFUN_PARAGRAPH_GOTO, but it seems best
1356 dr.screenUpdate(Update::Force | Update::FitCursor);
1361 case LFUN_PARAGRAPH_GOTO: {
1362 int const id = convert<int>(cmd.getArg(0));
1363 int const pos = convert<int>(cmd.getArg(1));
1365 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1366 b = theBufferList().next(b)) {
1368 DocIterator dit = b->getParFromID(id);
1370 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1374 LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1375 << " found in buffer `"
1376 << b->absFileName() << "'.");
1378 if (b == &buffer_) {
1382 dr.screenUpdate(Update::Force | Update::FitCursor);
1384 // Switch to other buffer view and resend cmd
1385 lyx::dispatch(FuncRequest(
1386 LFUN_BUFFER_SWITCH, b->absFileName()));
1394 case LFUN_NOTE_NEXT:
1395 gotoInset(this, NOTE_CODE, false);
1398 case LFUN_REFERENCE_NEXT: {
1399 vector<InsetCode> tmp;
1400 tmp.push_back(LABEL_CODE);
1401 tmp.push_back(REF_CODE);
1402 gotoInset(this, tmp, true);
1406 case LFUN_CHANGES_TRACK:
1407 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1410 case LFUN_CHANGES_OUTPUT:
1411 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1412 if (buffer_.params().outputChanges) {
1413 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1414 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1415 LaTeXFeatures::isAvailable("xcolor");
1417 if (!dvipost && !xcolorulem) {
1418 Alert::warning(_("Changes not shown in LaTeX output"),
1419 _("Changes will not be highlighted in LaTeX output, "
1420 "because neither dvipost nor xcolor/ulem are installed.\n"
1421 "Please install these packages or redefine "
1422 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1423 } else if (!xcolorulem) {
1424 Alert::warning(_("Changes not shown in LaTeX output"),
1425 _("Changes will not be highlighted in LaTeX output "
1426 "when using pdflatex, because xcolor and ulem are not installed.\n"
1427 "Please install both packages or redefine "
1428 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1433 case LFUN_CHANGE_NEXT:
1434 findNextChange(this);
1435 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1436 dr.screenUpdate(Update::Force | Update::FitCursor);
1439 case LFUN_CHANGE_PREVIOUS:
1440 findPreviousChange(this);
1441 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1442 dr.screenUpdate(Update::Force | Update::FitCursor);
1445 case LFUN_CHANGES_MERGE:
1446 if (findNextChange(this) || findPreviousChange(this)) {
1447 dr.screenUpdate(Update::Force | Update::FitCursor);
1448 dr.forceBufferUpdate();
1449 showDialog("changes");
1453 case LFUN_ALL_CHANGES_ACCEPT:
1454 // select complete document
1456 cur.selHandle(true);
1457 buffer_.text().cursorBottom(cur);
1458 // accept everything in a single step to support atomic undo
1459 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1460 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1461 dr.screenUpdate(Update::Force | Update::FitCursor);
1462 dr.forceBufferUpdate();
1465 case LFUN_ALL_CHANGES_REJECT:
1466 // select complete document
1468 cur.selHandle(true);
1469 buffer_.text().cursorBottom(cur);
1470 // reject everything in a single step to support atomic undo
1471 // Note: reject does not work recursively; the user may have to repeat the operation
1472 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1473 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1474 dr.screenUpdate(Update::Force | Update::FitCursor);
1475 dr.forceBufferUpdate();
1478 case LFUN_WORD_FIND_FORWARD:
1479 case LFUN_WORD_FIND_BACKWARD: {
1480 static docstring last_search;
1481 docstring searched_string;
1483 if (!cmd.argument().empty()) {
1484 last_search = cmd.argument();
1485 searched_string = cmd.argument();
1487 searched_string = last_search;
1490 if (searched_string.empty())
1493 bool const fw = act == LFUN_WORD_FIND_FORWARD;
1494 docstring const data =
1495 find2string(searched_string, true, false, fw);
1496 bool found = lyxfind(this, FuncRequest(LFUN_WORD_FIND, data));
1498 dr.screenUpdate(Update::Force | Update::FitCursor);
1502 case LFUN_WORD_FIND: {
1503 FuncRequest req = cmd;
1504 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1505 req = d->search_request_cache_;
1506 if (req.argument().empty()) {
1507 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1510 if (lyxfind(this, req))
1511 dr.screenUpdate(Update::Force | Update::FitCursor);
1513 message(_("String not found!"));
1514 d->search_request_cache_ = req;
1518 case LFUN_WORD_REPLACE: {
1519 bool has_deleted = false;
1520 if (cur.selection()) {
1521 DocIterator beg = cur.selectionBegin();
1522 DocIterator end = cur.selectionEnd();
1523 if (beg.pit() == end.pit()) {
1524 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1525 if (!cur.inMathed() && cur.paragraph().isDeleted(p)) {
1532 if (lyxreplace(this, cmd, has_deleted)) {
1533 dr.forceBufferUpdate();
1534 dr.screenUpdate(Update::Force | Update::FitCursor);
1539 case LFUN_WORD_FINDADV: {
1540 FindAndReplaceOptions opt;
1541 istringstream iss(to_utf8(cmd.argument()));
1543 if (findAdv(this, opt)) {
1544 dr.screenUpdate(Update::Force | Update::FitCursor);
1555 cur.clearSelection();
1556 dr.setMessage(from_utf8(N_("Mark off")));
1560 cur.clearSelection();
1562 dr.setMessage(from_utf8(N_("Mark on")));
1565 case LFUN_MARK_TOGGLE:
1566 cur.setSelection(false);
1569 dr.setMessage(from_utf8(N_("Mark removed")));
1572 dr.setMessage(from_utf8(N_("Mark set")));
1577 case LFUN_SCREEN_SHOW_CURSOR:
1581 case LFUN_SCREEN_RECENTER:
1585 case LFUN_BIBTEX_DATABASE_ADD: {
1586 Cursor tmpcur = cur;
1587 findInset(tmpcur, BIBTEX_CODE, false);
1588 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1591 if (inset->addDatabase(cmd.argument())) {
1592 buffer_.invalidateBibfileCache();
1593 dr.forceBufferUpdate();
1599 case LFUN_BIBTEX_DATABASE_DEL: {
1600 Cursor tmpcur = cur;
1601 findInset(tmpcur, BIBTEX_CODE, false);
1602 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1605 if (inset->delDatabase(cmd.argument())) {
1606 buffer_.invalidateBibfileCache();
1607 dr.forceBufferUpdate();
1613 case LFUN_STATISTICS: {
1614 DocIterator from, to;
1615 if (cur.selection()) {
1616 from = cur.selectionBegin();
1617 to = cur.selectionEnd();
1619 from = doc_iterator_begin(&buffer_);
1620 to = doc_iterator_end(&buffer_);
1622 int const words = countWords(from, to);
1623 int const chars = countChars(from, to, false);
1624 int const chars_blanks = countChars(from, to, true);
1626 if (cur.selection())
1627 message = _("Statistics for the selection:");
1629 message = _("Statistics for the document:");
1632 message += bformat(_("%1$d words"), words);
1634 message += _("One word");
1636 if (chars_blanks != 1)
1637 message += bformat(_("%1$d characters (including blanks)"),
1640 message += _("One character (including blanks)");
1643 message += bformat(_("%1$d characters (excluding blanks)"),
1646 message += _("One character (excluding blanks)");
1648 Alert::information(_("Statistics"), message);
1652 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1653 // turn compression on/off
1654 buffer_.params().compressed = !buffer_.params().compressed;
1657 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
1658 buffer_.params().output_sync = !buffer_.params().output_sync;
1661 case LFUN_SCREEN_UP:
1662 case LFUN_SCREEN_DOWN: {
1663 Point p = getPos(cur);
1664 // This code has been commented out to enable to scroll down a
1665 // document, even if there are large insets in it (see bug #5465).
1666 /*if (p.y_ < 0 || p.y_ > height_) {
1667 // The cursor is off-screen so recenter before proceeding.
1671 int const scrolled = scroll(act == LFUN_SCREEN_UP
1672 ? -height_ : height_);
1673 if (act == LFUN_SCREEN_UP && scrolled > -height_)
1675 if (act == LFUN_SCREEN_DOWN && scrolled < height_)
1676 p = Point(width_, height_);
1678 bool const in_texted = cur.inTexted();
1680 buffer_.changed(true);
1681 updateHoveredInset();
1683 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1684 true, act == LFUN_SCREEN_UP);
1685 //FIXME: what to do with cur.x_target()?
1686 bool update = in_texted && cur.bv().checkDepm(cur, old);
1689 dr.screenUpdate(Update::Force | Update::FitCursor);
1690 dr.forceBufferUpdate();
1697 dr.forceBufferUpdate();
1700 case LFUN_SCREEN_UP_SELECT: {
1701 cur.selHandle(true);
1702 if (isTopScreen()) {
1703 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1707 int y = getPos(cur).y_;
1708 int const ymin = y - height_ + defaultRowHeight();
1709 while (y > ymin && cur.up())
1713 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1717 case LFUN_SCREEN_DOWN_SELECT: {
1718 cur.selHandle(true);
1719 if (isBottomScreen()) {
1720 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1724 int y = getPos(cur).y_;
1725 int const ymax = y + height_ - defaultRowHeight();
1726 while (y < ymax && cur.down())
1730 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1735 // This would be in Buffer class if only Cursor did not
1736 // require a bufferview
1737 case LFUN_INSET_FORALL: {
1738 docstring const name = from_utf8(cmd.getArg(0));
1739 string const commandstr = cmd.getLongArg(1);
1740 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
1742 // an arbitrary number to limit number of iterations
1743 const int max_iter = 10000;
1745 Cursor & cur = d->cursor_;
1746 Cursor const savecur = cur;
1748 if (!cur.nextInset())
1750 cur.beginUndoGroup();
1751 while(cur && iterations < max_iter) {
1752 Inset * ins = cur.nextInset();
1755 docstring insname = ins->name();
1756 while (!insname.empty()) {
1757 if (insname == name || name == from_utf8("*")) {
1759 lyx::dispatch(fr, dr);
1763 size_t const i = insname.rfind(':');
1764 if (i == string::npos)
1766 insname = insname.substr(0, i);
1773 dr.screenUpdate(Update::Force);
1774 dr.forceBufferUpdate();
1776 if (iterations >= max_iter) {
1778 dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
1780 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
1785 case LFUN_BRANCH_ADD_INSERT: {
1786 docstring branch_name = from_utf8(cmd.getArg(0));
1787 if (branch_name.empty())
1788 if (!Alert::askForText(branch_name, _("Branch name")) ||
1789 branch_name.empty())
1792 DispatchResult drtmp;
1793 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
1794 if (drtmp.error()) {
1795 Alert::warning(_("Branch already exists"), drtmp.message());
1798 BranchList & branch_list = buffer_.params().branchlist();
1799 vector<docstring> const branches =
1800 getVectorFromString(branch_name, branch_list.separator());
1801 for (vector<docstring>::const_iterator it = branches.begin();
1802 it != branches.end(); ++it) {
1804 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch_name));
1809 case LFUN_KEYMAP_OFF:
1810 getIntl().keyMapOn(false);
1813 case LFUN_KEYMAP_PRIMARY:
1814 getIntl().keyMapPrim();
1817 case LFUN_KEYMAP_SECONDARY:
1818 getIntl().keyMapSec();
1821 case LFUN_KEYMAP_TOGGLE:
1822 getIntl().toggleKeyMap();
1825 case LFUN_DIALOG_SHOW_NEW_INSET: {
1826 string const name = cmd.getArg(0);
1827 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1828 if (decodeInsetParam(name, data, buffer_))
1829 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1831 lyxerr << "Inset type '" << name <<
1832 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
1836 case LFUN_CITATION_INSERT: {
1837 if (argument.empty()) {
1838 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1841 // we can have one optional argument, delimited by '|'
1842 // citation-insert <key>|<text_before>
1843 // this should be enhanced to also support text_after
1844 // and citation style
1845 string arg = argument;
1847 if (contains(argument, "|")) {
1848 arg = token(argument, '|', 0);
1849 opt1 = token(argument, '|', 1);
1851 InsetCommandParams icp(CITE_CODE);
1852 icp["key"] = from_utf8(arg);
1854 icp["before"] = from_utf8(opt1);
1855 string icstr = InsetCommand::params2string(icp);
1856 FuncRequest fr(LFUN_INSET_INSERT, icstr);
1861 case LFUN_INSET_APPLY: {
1862 string const name = cmd.getArg(0);
1863 Inset * inset = editedInset(name);
1865 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1869 // put cursor in front of inset.
1870 if (!setCursorFromInset(inset)) {
1871 LASSERT(false, break);
1874 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1875 inset->dispatch(cur, fr);
1876 dr.screenUpdate(cur.result().screenUpdate());
1877 if (cur.result().needBufferUpdate())
1878 dr.forceBufferUpdate();
1883 // OK, so try the Buffer itself...
1884 buffer_.dispatch(cmd, dr);
1885 dispatched = dr.dispatched();
1889 buffer_.undo().endUndoGroup();
1890 dr.dispatched(dispatched);
1894 docstring const BufferView::requestSelection()
1896 Cursor & cur = d->cursor_;
1898 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
1899 if (!cur.selection()) {
1900 d->xsel_cache_.set = false;
1904 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
1905 if (!d->xsel_cache_.set ||
1906 cur.top() != d->xsel_cache_.cursor ||
1907 cur.realAnchor().top() != d->xsel_cache_.anchor)
1909 d->xsel_cache_.cursor = cur.top();
1910 d->xsel_cache_.anchor = cur.realAnchor().top();
1911 d->xsel_cache_.set = cur.selection();
1912 return cur.selectionAsString(false);
1918 void BufferView::clearSelection()
1920 d->cursor_.clearSelection();
1921 // Clear the selection buffer. Otherwise a subsequent
1922 // middle-mouse-button paste would use the selection buffer,
1923 // not the more current external selection.
1924 cap::clearSelection();
1925 d->xsel_cache_.set = false;
1926 // The buffer did not really change, but this causes the
1927 // redraw we need because we cleared the selection above.
1928 buffer_.changed(false);
1932 void BufferView::resize(int width, int height)
1934 // Update from work area
1938 // Clear the paragraph height cache.
1939 d->par_height_.clear();
1940 // Redo the metrics.
1945 Inset const * BufferView::getCoveringInset(Text const & text,
1948 TextMetrics & tm = d->text_metrics_[&text];
1949 Inset * inset = tm.checkInsetHit(x, y);
1953 if (!inset->descendable(*this))
1954 // No need to go further down if the inset is not
1958 size_t cell_number = inset->nargs();
1959 // Check all the inner cell.
1960 for (size_t i = 0; i != cell_number; ++i) {
1961 Text const * inner_text = inset->getText(i);
1964 Inset const * inset_deeper =
1965 getCoveringInset(*inner_text, x, y);
1967 return inset_deeper;
1975 void BufferView::updateHoveredInset() const
1977 // Get inset under mouse, if there is one.
1978 int const x = d->mouse_position_cache_.x_;
1979 int const y = d->mouse_position_cache_.y_;
1980 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
1982 d->clickable_inset_ = covering_inset && covering_inset->clickable(x, y);
1984 if (covering_inset == d->last_inset_)
1985 // Same inset, no need to do anything...
1988 bool need_redraw = false;
1989 if (d->last_inset_) {
1990 // Remove the hint on the last hovered inset (if any).
1991 need_redraw |= d->last_inset_->setMouseHover(this, false);
1995 if (covering_inset && covering_inset->setMouseHover(this, true)) {
1997 // Only the insets that accept the hover state, do
1998 // clear the last_inset_, so only set the last_inset_
1999 // member if the hovered setting is accepted.
2000 d->last_inset_ = covering_inset;
2004 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
2005 << d->mouse_position_cache_.x_ << ", "
2006 << d->mouse_position_cache_.y_ << ")");
2008 d->update_strategy_ = DecorationUpdate;
2010 // This event (moving without mouse click) is not passed further.
2011 // This should be changed if it is further utilized.
2012 buffer_.changed(false);
2017 void BufferView::clearLastInset(Inset * inset) const
2019 if (d->last_inset_ != inset) {
2020 LYXERR0("Wrong last_inset!");
2021 LASSERT(false, /**/);
2027 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
2029 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
2031 // This is only called for mouse related events including
2032 // LFUN_FILE_OPEN generated by drag-and-drop.
2033 FuncRequest cmd = cmd0;
2035 Cursor old = cursor();
2037 cur.push(buffer_.inset());
2038 cur.setSelection(d->cursor_.selection());
2040 // Either the inset under the cursor or the
2041 // surrounding Text will handle this event.
2043 // make sure we stay within the screen...
2044 cmd.set_y(min(max(cmd.y(), -1), height_));
2046 d->mouse_position_cache_.x_ = cmd.x();
2047 d->mouse_position_cache_.y_ = cmd.y();
2049 if (cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
2050 updateHoveredInset();
2054 // Build temporary cursor.
2055 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x(), cmd.y());
2057 // Put anchor at the same position.
2060 cur.beginUndoGroup();
2062 // Try to dispatch to an non-editable inset near this position
2063 // via the temp cursor. If the inset wishes to change the real
2064 // cursor it has to do so explicitly by using
2065 // cur.bv().cursor() = cur; (or similar)
2067 inset->dispatch(cur, cmd);
2069 // Now dispatch to the temporary cursor. If the real cursor should
2070 // be modified, the inset's dispatch has to do so explicitly.
2071 if (!inset || !cur.result().dispatched())
2076 // Notify left insets
2079 bool badcursor = notifyCursorLeavesOrEnters(old, cur);
2081 cursor().fixIfBroken();
2084 // Do we have a selection?
2085 theSelection().haveSelection(cursor().selection());
2087 // If the command has been dispatched,
2088 if (cur.result().dispatched() || cur.result().screenUpdate())
2089 processUpdateFlags(cur.result().screenUpdate());
2093 void BufferView::lfunScroll(FuncRequest const & cmd)
2095 string const scroll_type = cmd.getArg(0);
2096 int scroll_step = 0;
2097 if (scroll_type == "line")
2098 scroll_step = d->scrollbarParameters_.single_step;
2099 else if (scroll_type == "page")
2100 scroll_step = d->scrollbarParameters_.page_step;
2103 string const scroll_quantity = cmd.getArg(1);
2104 if (scroll_quantity == "up")
2105 scrollUp(scroll_step);
2106 else if (scroll_quantity == "down")
2107 scrollDown(scroll_step);
2109 int const scroll_value = convert<int>(scroll_quantity);
2111 scroll(scroll_step * scroll_value);
2113 buffer_.changed(true);
2114 updateHoveredInset();
2118 int BufferView::minVisiblePart()
2120 return 2 * defaultRowHeight();
2124 int BufferView::scroll(int y)
2127 return scrollDown(y);
2129 return scrollUp(-y);
2134 int BufferView::scrollDown(int offset)
2136 Text * text = &buffer_.text();
2137 TextMetrics & tm = d->text_metrics_[text];
2138 int const ymax = height_ + offset;
2140 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2141 int bottom_pos = last.second->position() + last.second->descent();
2142 if (lyxrc.scroll_below_document)
2143 bottom_pos += height_ - minVisiblePart();
2144 if (last.first + 1 == int(text->paragraphs().size())) {
2145 if (bottom_pos <= height_)
2147 offset = min(offset, bottom_pos - height_);
2150 if (bottom_pos > ymax)
2152 tm.newParMetricsDown();
2154 d->anchor_ypos_ -= offset;
2159 int BufferView::scrollUp(int offset)
2161 Text * text = &buffer_.text();
2162 TextMetrics & tm = d->text_metrics_[text];
2163 int ymin = - offset;
2165 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2166 int top_pos = first.second->position() - first.second->ascent();
2167 if (first.first == 0) {
2170 offset = min(offset, - top_pos);
2175 tm.newParMetricsUp();
2177 d->anchor_ypos_ += offset;
2182 void BufferView::setCursorFromRow(int row)
2187 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
2191 buffer_.text().setCursor(d->cursor_, 0, 0);
2193 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
2198 bool BufferView::setCursorFromInset(Inset const * inset)
2200 // are we already there?
2201 if (cursor().nextInset() == inset)
2204 // Inset is not at cursor position. Find it in the document.
2207 while (cur && cur.nextInset() != inset)
2218 void BufferView::gotoLabel(docstring const & label)
2220 ListOfBuffers bufs = buffer().allRelatives();
2221 ListOfBuffers::iterator it = bufs.begin();
2222 for (; it != bufs.end(); ++it) {
2223 Buffer const * buf = *it;
2226 Toc & toc = buf->tocBackend().toc("label");
2227 TocIterator toc_it = toc.begin();
2228 TocIterator end = toc.end();
2229 for (; toc_it != end; ++toc_it) {
2230 if (label == toc_it->str()) {
2231 lyx::dispatch(toc_it->action());
2239 TextMetrics const & BufferView::textMetrics(Text const * t) const
2241 return const_cast<BufferView *>(this)->textMetrics(t);
2245 TextMetrics & BufferView::textMetrics(Text const * t)
2248 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
2249 if (tmc_it == d->text_metrics_.end()) {
2250 tmc_it = d->text_metrics_.insert(
2251 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
2253 return tmc_it->second;
2257 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2260 return textMetrics(t).parMetrics(pit);
2264 int BufferView::workHeight() const
2270 void BufferView::setCursor(DocIterator const & dit)
2273 size_t const n = dit.depth();
2274 for (size_t i = 0; i < n; ++i)
2275 dit[i].inset().edit(d->cursor_, true);
2277 d->cursor_.setCursor(dit);
2278 d->cursor_.setSelection(false);
2282 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2284 // Would be wrong to delete anything if we have a selection.
2285 if (cur.selection())
2288 bool need_anchor_change = false;
2289 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
2290 need_anchor_change);
2292 if (need_anchor_change)
2300 cur.forceBufferUpdate();
2301 buffer_.changed(true);
2306 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
2308 LASSERT(&cur.bv() == this, /**/);
2311 // this event will clear selection so we save selection for
2312 // persistent selection
2313 cap::saveSelection(cursor());
2315 d->cursor_.macroModeClose();
2317 // Has the cursor just left the inset?
2318 bool leftinset = (&d->cursor_.inset() != &cur.inset());
2320 d->cursor_.fixIfBroken();
2322 // FIXME: shift-mouse selection doesn't work well across insets.
2323 bool do_selection = select && &d->cursor_.normalAnchor().inset() == &cur.inset();
2325 // do the dEPM magic if needed
2326 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2327 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2328 // the leftinset bool would not be necessary (badcursor instead).
2329 bool update = leftinset;
2330 if (!do_selection && d->cursor_.inTexted())
2331 update |= checkDepm(cur, d->cursor_);
2334 d->cursor_.resetAnchor();
2335 d->cursor_.setCursor(cur);
2336 d->cursor_.boundary(cur.boundary());
2338 d->cursor_.setSelection();
2340 d->cursor_.clearSelection();
2342 d->cursor_.finishUndo();
2343 d->cursor_.setCurrentFont();
2345 cur.forceBufferUpdate();
2350 void BufferView::putSelectionAt(DocIterator const & cur,
2351 int length, bool backwards)
2353 d->cursor_.clearSelection();
2359 d->cursor_.pos() += length;
2360 d->cursor_.setSelection(d->cursor_, -length);
2362 d->cursor_.setSelection(d->cursor_, length);
2367 Cursor & BufferView::cursor()
2373 Cursor const & BufferView::cursor() const
2379 pit_type BufferView::anchor_ref() const
2381 return d->anchor_pit_;
2385 bool BufferView::singleParUpdate()
2387 Text & buftext = buffer_.text();
2388 pit_type const bottom_pit = d->cursor_.bottom().pit();
2389 TextMetrics & tm = textMetrics(&buftext);
2390 int old_height = tm.parMetrics(bottom_pit).height();
2392 // make sure inline completion pointer is ok
2393 if (d->inlineCompletionPos_.fixIfBroken())
2394 d->inlineCompletionPos_ = DocIterator();
2396 // In Single Paragraph mode, rebreak only
2397 // the (main text, not inset!) paragraph containing the cursor.
2398 // (if this paragraph contains insets etc., rebreaking will
2399 // recursively descend)
2400 tm.redoParagraph(bottom_pit);
2401 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
2402 if (pm.height() != old_height)
2403 // Paragraph height has changed so we cannot proceed to
2404 // the singlePar optimisation.
2407 d->update_strategy_ = SingleParUpdate;
2409 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2410 << " y2: " << pm.position() + pm.descent()
2411 << " pit: " << bottom_pit
2412 << " singlepar: 1");
2417 void BufferView::updateMetrics()
2419 if (height_ == 0 || width_ == 0)
2422 Text & buftext = buffer_.text();
2423 pit_type const npit = int(buftext.paragraphs().size());
2425 // Clear out the position cache in case of full screen redraw,
2426 d->coord_cache_.clear();
2428 // Clear out paragraph metrics to avoid having invalid metrics
2429 // in the cache from paragraphs not relayouted below
2430 // The complete text metrics will be redone.
2431 d->text_metrics_.clear();
2433 TextMetrics & tm = textMetrics(&buftext);
2435 // make sure inline completion pointer is ok
2436 if (d->inlineCompletionPos_.fixIfBroken())
2437 d->inlineCompletionPos_ = DocIterator();
2439 if (d->anchor_pit_ >= npit)
2440 // The anchor pit must have been deleted...
2441 d->anchor_pit_ = npit - 1;
2443 // Rebreak anchor paragraph.
2444 tm.redoParagraph(d->anchor_pit_);
2445 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2448 if (d->anchor_pit_ == 0) {
2449 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2451 // Complete buffer visible? Then it's easy.
2452 if (scrollRange == 0)
2453 d->anchor_ypos_ = anchor_pm.ascent();
2455 // FIXME: Some clever handling needed to show
2456 // the _first_ paragraph up to the top if the cursor is
2457 // in the first line.
2459 anchor_pm.setPosition(d->anchor_ypos_);
2461 LYXERR(Debug::PAINTING, "metrics: "
2462 << " anchor pit = " << d->anchor_pit_
2463 << " anchor ypos = " << d->anchor_ypos_);
2465 // Redo paragraphs above anchor if necessary.
2466 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2467 // We are now just above the anchor paragraph.
2468 pit_type pit1 = d->anchor_pit_ - 1;
2469 for (; pit1 >= 0 && y1 >= 0; --pit1) {
2470 tm.redoParagraph(pit1);
2471 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2473 // Save the paragraph position in the cache.
2478 // Redo paragraphs below the anchor if necessary.
2479 int y2 = d->anchor_ypos_ + anchor_pm.descent();
2480 // We are now just below the anchor paragraph.
2481 pit_type pit2 = d->anchor_pit_ + 1;
2482 for (; pit2 < npit && y2 <= height_; ++pit2) {
2483 tm.redoParagraph(pit2);
2484 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2486 // Save the paragraph position in the cache.
2491 LYXERR(Debug::PAINTING, "Metrics: "
2492 << " anchor pit = " << d->anchor_pit_
2493 << " anchor ypos = " << d->anchor_ypos_
2496 << " pit1 = " << pit1
2497 << " pit2 = " << pit2);
2499 d->update_strategy_ = FullScreenUpdate;
2501 if (lyxerr.debugging(Debug::WORKAREA)) {
2502 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2503 d->coord_cache_.dump();
2508 void BufferView::insertLyXFile(FileName const & fname)
2510 LASSERT(d->cursor_.inTexted(), /**/);
2512 // Get absolute path of file and add ".lyx"
2513 // to the filename if necessary
2514 FileName filename = fileSearch(string(), fname.absFileName(), "lyx");
2516 docstring const disp_fn = makeDisplayPath(filename.absFileName());
2517 // emit message signal.
2518 message(bformat(_("Inserting document %1$s..."), disp_fn));
2521 Buffer buf(filename.absFileName(), false);
2522 if (buf.loadLyXFile() == Buffer::ReadSuccess) {
2523 ErrorList & el = buffer_.errorList("Parse");
2524 // Copy the inserted document error list into the current buffer one.
2525 el = buf.errorList("Parse");
2526 buffer_.undo().recordUndo(d->cursor_);
2527 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2528 buf.params().documentClassPtr(), el);
2529 res = _("Document %1$s inserted.");
2531 res = _("Could not insert document %1$s");
2534 buffer_.changed(true);
2535 // emit message signal.
2536 message(bformat(res, disp_fn));
2540 Point BufferView::coordOffset(DocIterator const & dit) const
2546 // Addup contribution of nested insets, from inside to outside,
2547 // keeping the outer paragraph for a special handling below
2548 for (size_t i = dit.depth() - 1; i >= 1; --i) {
2549 CursorSlice const & sl = dit[i];
2553 // get relative position inside sl.inset()
2554 sl.inset().cursorPos(*this, sl, dit.boundary() && (i + 1 == dit.depth()), xx, yy);
2556 // Make relative position inside of the edited inset relative to sl.inset()
2560 // In case of an RTL inset, the edited inset will be positioned to the left
2563 bool boundary_i = dit.boundary() && i + 1 == dit.depth();
2564 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2569 // remember width for the case that sl.inset() is positioned in an RTL inset
2570 if (i && dit[i - 1].text()) {
2571 // If this Inset is inside a Text Inset, retrieve the Dimension
2572 // from the containing text instead of using Inset::dimension() which
2573 // might not be implemented.
2574 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2575 // elimination of Inset::dim_ cache. This coordOffset() method needs
2576 // to be rewritten in light of the new design.
2577 Dimension const & dim = parMetrics(dit[i - 1].text(),
2578 dit[i - 1].pit()).insetDimension(&sl.inset());
2581 Dimension const dim = sl.inset().dimension(*this);
2585 //lyxerr << "Cursor::getPos, i: "
2586 // << i << " x: " << xx << " y: " << y << endl;
2589 // Add contribution of initial rows of outermost paragraph
2590 CursorSlice const & sl = dit[0];
2591 TextMetrics const & tm = textMetrics(sl.text());
2592 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2593 LASSERT(!pm.rows().empty(), /**/);
2594 y -= pm.rows()[0].ascent();
2596 // FIXME: document this mess
2598 if (sl.pos() > 0 && dit.depth() == 1) {
2600 if (pos && dit.boundary())
2602 // lyxerr << "coordOffset: boundary:" << dit.boundary() << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2603 rend = pm.pos2row(pos);
2605 rend = pm.pos2row(sl.pos());
2607 size_t rend = pm.pos2row(sl.pos());
2609 for (size_t rit = 0; rit != rend; ++rit)
2610 y += pm.rows()[rit].height();
2611 y += pm.rows()[rend].ascent();
2613 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2615 // Make relative position from the nested inset now bufferview absolute.
2616 int xx = bottom_tm.cursorX(dit.bottom(), dit.boundary() && dit.depth() == 1);
2619 // In the RTL case place the nested inset at the left of the cursor in
2620 // the outer paragraph
2621 bool boundary_1 = dit.boundary() && 1 == dit.depth();
2622 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2630 Point BufferView::getPos(DocIterator const & dit) const
2632 if (!paragraphVisible(dit))
2633 return Point(-1, -1);
2635 CursorSlice const & bot = dit.bottom();
2636 TextMetrics const & tm = textMetrics(bot.text());
2638 // offset from outer paragraph
2639 Point p = coordOffset(dit);
2640 p.y_ += tm.parMetrics(bot.pit()).position();
2645 bool BufferView::paragraphVisible(DocIterator const & dit) const
2647 CursorSlice const & bot = dit.bottom();
2648 TextMetrics const & tm = textMetrics(bot.text());
2650 return tm.contains(bot.pit());
2654 void BufferView::cursorPosAndHeight(Point & p, int & h) const
2656 Cursor const & cur = cursor();
2657 Font const font = cur.getFont();
2658 frontend::FontMetrics const & fm = theFontMetrics(font);
2659 int const asc = fm.maxAscent();
2660 int const des = fm.maxDescent();
2667 bool BufferView::cursorInView(Point const & p, int h) const
2669 Cursor const & cur = cursor();
2670 // does the cursor touch the screen ?
2671 if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
2677 void BufferView::draw(frontend::Painter & pain)
2679 if (height_ == 0 || width_ == 0)
2681 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2683 Text & text = buffer_.text();
2684 TextMetrics const & tm = d->text_metrics_[&text];
2685 int const y = tm.first().second->position();
2686 PainterInfo pi(this, pain);
2688 switch (d->update_strategy_) {
2690 case NoScreenUpdate:
2691 // If no screen painting is actually needed, only some the different
2692 // coordinates of insets and paragraphs needs to be updated.
2693 pi.full_repaint = true;
2694 pi.pain.setDrawingEnabled(false);
2698 case SingleParUpdate:
2699 pi.full_repaint = false;
2700 // In general, only the current row of the outermost paragraph
2701 // will be redrawn. Particular cases where selection spans
2702 // multiple paragraph are correctly detected in TextMetrics.
2706 case DecorationUpdate:
2707 // FIXME: We should also distinguish DecorationUpdate to avoid text
2708 // drawing if possible. This is not possible to do easily right now
2709 // because of the single backing pixmap.
2711 case FullScreenUpdate:
2712 // The whole screen, including insets, will be refreshed.
2713 pi.full_repaint = true;
2715 // Clear background.
2716 pain.fillRectangle(0, 0, width_, height_,
2717 pi.backgroundColor(&buffer_.inset()));
2722 // and possibly grey out below
2723 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2724 int const y2 = lastpm.second->position() + lastpm.second->descent();
2727 Color color = buffer().isInternal()
2728 ? Color_background : Color_bottomarea;
2729 pain.fillRectangle(0, y2, width_, height_ - y2, color);
2733 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
2735 // The scrollbar needs an update.
2738 // Normalize anchor for next time
2739 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2740 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2741 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2742 ParagraphMetrics const & pm = tm.parMetrics(pit);
2743 if (pm.position() + pm.descent() > 0) {
2744 d->anchor_pit_ = pit;
2745 d->anchor_ypos_ = pm.position();
2749 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2750 << " anchor ypos = " << d->anchor_ypos_);
2754 void BufferView::message(docstring const & msg)
2757 d->gui_->message(msg);
2761 void BufferView::showDialog(string const & name)
2764 d->gui_->showDialog(name, string());
2768 void BufferView::showDialog(string const & name,
2769 string const & data, Inset * inset)
2772 d->gui_->showDialog(name, data, inset);
2776 void BufferView::updateDialog(string const & name, string const & data)
2779 d->gui_->updateDialog(name, data);
2783 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2789 // FIXME: Move this out of BufferView again
2790 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2792 if (!fname.isReadableFile()) {
2793 docstring const error = from_ascii(strerror(errno));
2794 docstring const file = makeDisplayPath(fname.absFileName(), 50);
2795 docstring const text =
2796 bformat(_("Could not read the specified document\n"
2797 "%1$s\ndue to the error: %2$s"), file, error);
2798 Alert::error(_("Could not read file"), text);
2802 if (!fname.isReadableFile()) {
2803 docstring const file = makeDisplayPath(fname.absFileName(), 50);
2804 docstring const text =
2805 bformat(_("%1$s\n is not readable."), file);
2806 Alert::error(_("Could not open file"), text);
2810 // FIXME UNICODE: We don't know the encoding of the file
2811 docstring file_content = fname.fileContents("UTF-8");
2812 if (file_content.empty()) {
2813 Alert::error(_("Reading not UTF-8 encoded file"),
2814 _("The file is not UTF-8 encoded.\n"
2815 "It will be read as local 8Bit-encoded.\n"
2816 "If this does not give the correct result\n"
2817 "then please change the encoding of the file\n"
2818 "to UTF-8 with a program other than LyX.\n"));
2819 file_content = fname.fileContents("local8bit");
2822 return normalize_c(file_content);
2826 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2828 docstring const tmpstr = contentsOfPlaintextFile(f);
2833 Cursor & cur = cursor();
2834 cap::replaceSelection(cur);
2835 buffer_.undo().recordUndo(cur);
2837 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
2839 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
2841 buffer_.changed(true);
2845 docstring const & BufferView::inlineCompletion() const
2847 return d->inlineCompletion_;
2851 size_t const & BufferView::inlineCompletionUniqueChars() const
2853 return d->inlineCompletionUniqueChars_;
2857 DocIterator const & BufferView::inlineCompletionPos() const
2859 return d->inlineCompletionPos_;
2863 void BufferView::resetInlineCompletionPos()
2865 d->inlineCompletionPos_ = DocIterator();
2869 bool samePar(DocIterator const & a, DocIterator const & b)
2871 if (a.empty() && b.empty())
2873 if (a.empty() || b.empty())
2875 if (a.depth() != b.depth())
2877 return &a.innerParagraph() == &b.innerParagraph();
2881 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos,
2882 docstring const & completion, size_t uniqueChars)
2884 uniqueChars = min(completion.size(), uniqueChars);
2885 bool changed = d->inlineCompletion_ != completion
2886 || d->inlineCompletionUniqueChars_ != uniqueChars;
2887 bool singlePar = true;
2888 d->inlineCompletion_ = completion;
2889 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
2891 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2894 DocIterator const & old = d->inlineCompletionPos_;
2896 //lyxerr << "inlineCompletionPos changed" << std::endl;
2897 // old or pos are in another paragraph?
2898 if ((!samePar(cur, pos) && !pos.empty())
2899 || (!samePar(cur, old) && !old.empty())) {
2901 //lyxerr << "different paragraph" << std::endl;
2903 d->inlineCompletionPos_ = pos;
2908 if (singlePar && !(cur.result().screenUpdate() & Update::Force))
2909 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
2911 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::Force);
2916 bool BufferView::clickableInset() const
2918 return d->clickable_inset_;