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 // Don't eat cpu time for each keystroke
704 if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
707 d->bookmark_edit_position_ = d->cursor_.paragraph().id();
711 void BufferView::saveBookmark(unsigned int idx)
713 // tentatively save bookmark, id and pos will be used to
714 // acturately locate a bookmark in a 'live' lyx session.
715 // pit and pos will be updated with bottom level pit/pos
717 if (!buffer_.isInternal()) {
718 theSession().bookmarks().save(
720 d->cursor_.bottom().pit(),
721 d->cursor_.bottom().pos(),
722 d->cursor_.paragraph().id(),
727 // emit message signal.
728 message(_("Save bookmark"));
733 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
734 int top_id, pos_type top_pos)
736 bool success = false;
739 d->cursor_.clearSelection();
741 // if a valid par_id is given, try it first
742 // This is the case for a 'live' bookmark when unique paragraph ID
743 // is used to track bookmarks.
745 dit = buffer_.getParFromID(top_id);
747 dit.pos() = min(dit.paragraph().size(), top_pos);
748 // Some slices of the iterator may not be
749 // reachable (e.g. closed collapsable inset)
750 // so the dociterator may need to be
751 // shortened. Otherwise, setCursor may crash
752 // lyx when the cursor can not be set to these
754 size_t const n = dit.depth();
755 for (size_t i = 0; i < n; ++i)
756 if (!dit[i].inset().editable()) {
764 // if top_id == 0, or searching through top_id failed
765 // This is the case for a 'restored' bookmark when only bottom
766 // (document level) pit was saved. Because of this, bookmark
767 // restoration is inaccurate. If a bookmark was within an inset,
768 // it will be restored to the left of the outmost inset that contains
770 if (bottom_pit < int(buffer_.paragraphs().size())) {
771 dit = doc_iterator_begin(&buffer_);
773 dit.pit() = bottom_pit;
774 dit.pos() = min(bottom_pos, dit.paragraph().size());
779 // Note: only bottom (document) level pit is set.
781 // set the current font.
782 d->cursor_.setCurrentFont();
783 // To center the screen on this new position we need the
784 // paragraph position which is computed at draw() time.
785 // So we need a redraw!
786 buffer_.changed(false);
795 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
797 if (lyxrc.rtl_support) {
798 if (d->cursor_.real_current_font.isRightToLeft()) {
799 if (d->intl_.keymap == Intl::PRIMARY)
800 d->intl_.keyMapSec();
802 if (d->intl_.keymap == Intl::SECONDARY)
803 d->intl_.keyMapPrim();
807 d->intl_.getTransManager().translateAndInsert(c, t, cur);
811 int BufferView::workWidth() const
817 void BufferView::recenter()
819 showCursor(d->cursor_, true, true);
823 void BufferView::showCursor()
825 showCursor(d->cursor_, false, true);
829 void BufferView::showCursor(DocIterator const & dit,
830 bool recenter, bool update)
832 if (scrollToCursor(dit, recenter) && update) {
833 buffer_.changed(true);
834 updateHoveredInset();
839 void BufferView::scrollToCursor()
841 if (scrollToCursor(d->cursor_, false)) {
842 buffer_.changed(true);
843 updateHoveredInset();
848 bool BufferView::scrollToCursor(DocIterator const & dit, bool recenter)
850 // We are not properly started yet, delay until resizing is
855 LYXERR(Debug::SCROLLING, "recentering!");
857 CursorSlice const & bot = dit.bottom();
858 TextMetrics & tm = d->text_metrics_[bot.text()];
860 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
861 int bot_pit = bot.pit();
862 if (bot_pit > max_pit) {
863 // FIXME: Why does this happen?
864 LYXERR0("bottom pit is greater that max pit: "
865 << bot_pit << " > " << max_pit);
869 if (bot_pit == tm.first().first - 1)
870 tm.newParMetricsUp();
871 else if (bot_pit == tm.last().first + 1)
872 tm.newParMetricsDown();
874 if (tm.contains(bot_pit)) {
875 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
876 LASSERT(!pm.rows().empty(), /**/);
877 // FIXME: smooth scrolling doesn't work in mathed.
878 CursorSlice const & cs = dit.innerTextSlice();
879 int offset = coordOffset(dit).y_;
880 int ypos = pm.position() + offset;
881 Dimension const & row_dim =
882 pm.getRow(cs.pos(), dit.boundary()).dimension();
885 scrolled = scroll(ypos - height_/2);
887 // If the top part of the row falls of the screen, we scroll
888 // up to align the top of the row with the top of the screen.
889 else if (ypos - row_dim.ascent() < 0)
890 scrolled = scrollUp(-ypos + row_dim.ascent());
892 // If the bottom of the row falls of the screen, we scroll down.
893 // However, we have to be careful not to scroll that much that
894 // the top falls of the screen.
895 else if (ypos + row_dim.descent() > height_) {
896 int ynew = height_ - row_dim.descent();
897 if (ynew < row_dim.ascent())
898 ynew = row_dim.ascent();
899 int const scroll = ypos - ynew;
900 scrolled = scrollDown(scroll);
903 // else, nothing to do, the cursor is already visible so we just return.
904 return scrolled != 0;
907 // fix inline completion position
908 if (d->inlineCompletionPos_.fixIfBroken())
909 d->inlineCompletionPos_ = DocIterator();
911 tm.redoParagraph(bot_pit);
912 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
913 int offset = coordOffset(dit).y_;
915 d->anchor_pit_ = bot_pit;
916 CursorSlice const & cs = dit.innerTextSlice();
917 Dimension const & row_dim =
918 pm.getRow(cs.pos(), dit.boundary()).dimension();
921 d->anchor_ypos_ = height_/2;
922 else if (d->anchor_pit_ == 0)
923 d->anchor_ypos_ = offset + pm.ascent();
924 else if (d->anchor_pit_ == max_pit)
925 d->anchor_ypos_ = height_ - offset - row_dim.descent();
926 else if (offset > height_)
927 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
929 d->anchor_ypos_ = defaultRowHeight() * 2;
935 void BufferView::updateDocumentClass(DocumentClass const * const olddc)
937 message(_("Converting document to new document class..."));
939 StableDocIterator backcur(d->cursor_);
940 ErrorList & el = buffer_.errorList("Class Switch");
941 cap::switchBetweenClasses(
942 olddc, buffer_.params().documentClassPtr(),
943 static_cast<InsetText &>(buffer_.inset()), el);
945 setCursor(backcur.asDocIterator(&buffer_));
947 buffer_.errors("Class Switch");
950 /** Return the change status at cursor position, taking in account the
951 * status at each level of the document iterator (a table in a deleted
952 * footnote is deleted).
953 * When \param outer is true, the top slice is not looked at.
955 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
957 size_t const depth = dit.depth() - (outer ? 1 : 0);
959 for (size_t i = 0 ; i < depth ; ++i) {
960 CursorSlice const & slice = dit[i];
961 if (!slice.inset().inMathed()
962 && slice.pos() < slice.paragraph().size()) {
963 Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
964 if (ch != Change::UNCHANGED)
968 return Change::UNCHANGED;
972 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
974 FuncCode const act = cmd.action();
976 // Can we use a readonly buffer?
977 if (buffer_.isReadonly()
978 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
979 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
980 flag.message(from_utf8(N_("Document is read-only")));
981 flag.setEnabled(false);
985 // Are we in a DELETED change-tracking region?
986 if (lookupChangeType(d->cursor_, true) == Change::DELETED
987 && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
988 && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
989 flag.message(from_utf8(N_("This portion of the document is deleted.")));
990 flag.setEnabled(false);
994 Cursor & cur = d->cursor_;
996 if (cur.getStatus(cmd, flag))
1001 // FIXME: This is a bit problematic because we don't check if this is
1002 // a document BufferView or not for these LFUNs. We probably have to
1003 // dispatch both to currentBufferView() and, if that fails,
1004 // to documentBufferView(); same as we do now for current Buffer and
1005 // document Buffer. Ideally those LFUN should go to Buffer as they
1006 // operate on the full Buffer and the cursor is only needed either for
1007 // an Undo record or to restore a cursor position. But we don't know
1008 // how to do that inside Buffer of course.
1009 case LFUN_BUFFER_PARAMS_APPLY:
1010 case LFUN_LAYOUT_MODULES_CLEAR:
1011 case LFUN_LAYOUT_MODULE_ADD:
1012 case LFUN_LAYOUT_RELOAD:
1013 case LFUN_TEXTCLASS_APPLY:
1014 case LFUN_TEXTCLASS_LOAD:
1015 flag.setEnabled(!buffer_.isReadonly());
1019 // We do not use the LyXAction flag for readonly because Undo sets the
1020 // buffer clean/dirty status by itself.
1021 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasUndoStack());
1024 // We do not use the LyXAction flag for readonly because Redo sets the
1025 // buffer clean/dirty status by itself.
1026 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasRedoStack());
1028 case LFUN_FILE_INSERT:
1029 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1030 case LFUN_FILE_INSERT_PLAINTEXT:
1031 case LFUN_BOOKMARK_SAVE:
1032 // FIXME: Actually, these LFUNS should be moved to Text
1033 flag.setEnabled(cur.inTexted());
1036 case LFUN_FONT_STATE:
1037 case LFUN_LABEL_INSERT:
1038 case LFUN_INFO_INSERT:
1039 case LFUN_PARAGRAPH_GOTO:
1040 case LFUN_NOTE_NEXT:
1041 case LFUN_REFERENCE_NEXT:
1042 case LFUN_WORD_FIND:
1043 case LFUN_WORD_FIND_FORWARD:
1044 case LFUN_WORD_FIND_BACKWARD:
1045 case LFUN_WORD_FINDADV:
1046 case LFUN_WORD_REPLACE:
1049 case LFUN_MARK_TOGGLE:
1050 case LFUN_SCREEN_RECENTER:
1051 case LFUN_SCREEN_SHOW_CURSOR:
1052 case LFUN_BIBTEX_DATABASE_ADD:
1053 case LFUN_BIBTEX_DATABASE_DEL:
1054 case LFUN_STATISTICS:
1055 case LFUN_BRANCH_ADD_INSERT:
1056 case LFUN_KEYMAP_OFF:
1057 case LFUN_KEYMAP_PRIMARY:
1058 case LFUN_KEYMAP_SECONDARY:
1059 case LFUN_KEYMAP_TOGGLE:
1060 flag.setEnabled(true);
1063 case LFUN_LABEL_GOTO: {
1064 flag.setEnabled(!cmd.argument().empty()
1065 || getInsetByCode<InsetRef>(cur, REF_CODE));
1069 case LFUN_CHANGES_TRACK:
1070 flag.setEnabled(true);
1071 flag.setOnOff(buffer_.params().trackChanges);
1074 case LFUN_CHANGES_OUTPUT:
1075 flag.setEnabled(true);
1076 flag.setOnOff(buffer_.params().outputChanges);
1079 case LFUN_CHANGES_MERGE:
1080 case LFUN_CHANGE_NEXT:
1081 case LFUN_CHANGE_PREVIOUS:
1082 case LFUN_ALL_CHANGES_ACCEPT:
1083 case LFUN_ALL_CHANGES_REJECT:
1084 // TODO: context-sensitive enabling of LFUNs
1085 // In principle, these command should only be enabled if there
1086 // is a change in the document. However, without proper
1087 // optimizations, this will inevitably result in poor performance.
1088 flag.setEnabled(true);
1091 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
1092 flag.setOnOff(buffer_.params().compressed);
1096 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC: {
1097 flag.setOnOff(buffer_.params().output_sync);
1101 case LFUN_SCREEN_UP:
1102 case LFUN_SCREEN_DOWN:
1104 case LFUN_SCREEN_UP_SELECT:
1105 case LFUN_SCREEN_DOWN_SELECT:
1106 case LFUN_INSET_FORALL:
1107 flag.setEnabled(true);
1110 case LFUN_LAYOUT_TABULAR:
1111 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1115 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1118 case LFUN_LAYOUT_PARAGRAPH:
1119 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1122 case LFUN_DIALOG_SHOW_NEW_INSET:
1123 // FIXME: this is wrong, but I do not understand the
1125 if (cur.inset().lyxCode() == CAPTION_CODE)
1126 return cur.inset().getStatus(cur, cmd, flag);
1127 // FIXME we should consider passthru paragraphs too.
1128 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1131 case LFUN_CITATION_INSERT: {
1132 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1133 // FIXME: This could turn in a recursive hell.
1134 // Shouldn't we use Buffer::getStatus() instead?
1135 flag.setEnabled(lyx::getStatus(fr).enabled());
1138 case LFUN_INSET_APPLY: {
1139 string const name = cmd.getArg(0);
1140 Inset * inset = editedInset(name);
1142 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1143 if (!inset->getStatus(cur, fr, flag)) {
1144 // Every inset is supposed to handle this
1145 LASSERT(false, break);
1148 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1149 flag = lyx::getStatus(fr);
1162 Inset * BufferView::editedInset(string const & name) const
1164 map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1165 return it == d->edited_insets_.end() ? 0 : it->second;
1169 void BufferView::editInset(string const & name, Inset * inset)
1171 d->edited_insets_[name] = inset;
1175 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1177 //lyxerr << [ cmd = " << cmd << "]" << endl;
1179 // Make sure that the cached BufferView is correct.
1180 LYXERR(Debug::ACTION, " action[" << cmd.action() << ']'
1181 << " arg[" << to_utf8(cmd.argument()) << ']'
1182 << " x[" << cmd.x() << ']'
1183 << " y[" << cmd.y() << ']'
1184 << " button[" << cmd.button() << ']');
1186 string const argument = to_utf8(cmd.argument());
1187 Cursor & cur = d->cursor_;
1189 // Don't dispatch function that does not apply to internal buffers.
1190 if (buffer_.isInternal()
1191 && lyxaction.funcHasFlag(cmd.action(), LyXAction::NoInternal))
1194 // We'll set this back to false if need be.
1195 bool dispatched = true;
1196 buffer_.undo().beginUndoGroup();
1198 FuncCode const act = cmd.action();
1201 case LFUN_BUFFER_PARAMS_APPLY: {
1202 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1203 cur.recordUndoFullDocument();
1204 istringstream ss(to_utf8(cmd.argument()));
1207 int const unknown_tokens = buffer_.readHeader(lex);
1208 if (unknown_tokens != 0) {
1209 LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1210 << unknown_tokens << " unknown token"
1211 << (unknown_tokens == 1 ? "" : "s"));
1213 updateDocumentClass(oldClass);
1215 // We are most certainly here because of a change in the document
1216 // It is then better to make sure that all dialogs are in sync with
1217 // current document settings.
1218 dr.screenUpdate(Update::Force | Update::FitCursor);
1219 dr.forceBufferUpdate();
1223 case LFUN_LAYOUT_MODULES_CLEAR: {
1224 DocumentClass const * const oldClass =
1225 buffer_.params().documentClassPtr();
1226 cur.recordUndoFullDocument();
1227 buffer_.params().clearLayoutModules();
1228 buffer_.params().makeDocumentClass();
1229 updateDocumentClass(oldClass);
1230 dr.screenUpdate(Update::Force);
1231 dr.forceBufferUpdate();
1235 case LFUN_LAYOUT_MODULE_ADD: {
1236 BufferParams const & params = buffer_.params();
1237 if (!params.moduleCanBeAdded(argument)) {
1238 LYXERR0("Module `" << argument <<
1239 "' cannot be added due to failed requirements or "
1240 "conflicts with installed modules.");
1243 DocumentClass const * const oldClass = params.documentClassPtr();
1244 cur.recordUndoFullDocument();
1245 buffer_.params().addLayoutModule(argument);
1246 buffer_.params().makeDocumentClass();
1247 updateDocumentClass(oldClass);
1248 dr.screenUpdate(Update::Force);
1249 dr.forceBufferUpdate();
1253 case LFUN_TEXTCLASS_APPLY: {
1254 // since this shortcircuits, the second call is made only if
1256 bool const success =
1257 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1258 LayoutFileList::get().load(argument, buffer_.filePath());
1260 docstring s = bformat(_("The document class `%1$s' "
1261 "could not be loaded."), from_utf8(argument));
1262 frontend::Alert::error(_("Could not load class"), s);
1266 LayoutFile const * old_layout = buffer_.params().baseClass();
1267 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1269 if (old_layout == new_layout)
1273 // Save the old, possibly modular, layout for use in conversion.
1274 DocumentClass const * const oldDocClass =
1275 buffer_.params().documentClassPtr();
1276 cur.recordUndoFullDocument();
1277 buffer_.params().setBaseClass(argument);
1278 buffer_.params().makeDocumentClass();
1279 updateDocumentClass(oldDocClass);
1280 dr.screenUpdate(Update::Force);
1281 dr.forceBufferUpdate();
1285 case LFUN_TEXTCLASS_LOAD: {
1286 // since this shortcircuits, the second call is made only if
1288 bool const success =
1289 LayoutFileList::get().load(argument, buffer_.temppath()) ||
1290 LayoutFileList::get().load(argument, buffer_.filePath());
1292 docstring s = bformat(_("The document class `%1$s' "
1293 "could not be loaded."), from_utf8(argument));
1294 frontend::Alert::error(_("Could not load class"), s);
1299 case LFUN_LAYOUT_RELOAD: {
1300 DocumentClass const * const oldClass = buffer_.params().documentClassPtr();
1301 LayoutFileIndex bc = buffer_.params().baseClassID();
1302 LayoutFileList::get().reset(bc);
1303 buffer_.params().setBaseClass(bc);
1304 buffer_.params().makeDocumentClass();
1305 updateDocumentClass(oldClass);
1306 dr.screenUpdate(Update::Force);
1307 dr.forceBufferUpdate();
1312 dr.setMessage(_("Undo"));
1313 cur.clearSelection();
1314 if (!cur.textUndo())
1315 dr.setMessage(_("No further undo information"));
1317 dr.screenUpdate(Update::Force | Update::FitCursor);
1318 dr.forceBufferUpdate();
1322 dr.setMessage(_("Redo"));
1323 cur.clearSelection();
1324 if (!cur.textRedo())
1325 dr.setMessage(_("No further redo information"));
1327 dr.screenUpdate(Update::Force | Update::FitCursor);
1328 dr.forceBufferUpdate();
1331 case LFUN_FONT_STATE:
1332 dr.setMessage(cur.currentState());
1335 case LFUN_BOOKMARK_SAVE:
1336 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1339 case LFUN_LABEL_GOTO: {
1340 docstring label = cmd.argument();
1341 if (label.empty()) {
1343 getInsetByCode<InsetRef>(cur, REF_CODE);
1345 label = inset->getParam("reference");
1346 // persistent=false: use temp_bookmark
1350 if (!label.empty()) {
1352 // at the moment, this is redundant, since gotoLabel will
1353 // eventually call LFUN_PARAGRAPH_GOTO, but it seems best
1355 dr.screenUpdate(Update::Force | Update::FitCursor);
1360 case LFUN_PARAGRAPH_GOTO: {
1361 int const id = convert<int>(cmd.getArg(0));
1362 int const pos = convert<int>(cmd.getArg(1));
1364 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1365 b = theBufferList().next(b)) {
1367 DocIterator dit = b->getParFromID(id);
1369 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1373 LYXERR(Debug::INFO, "Paragraph " << dit.paragraph().id()
1374 << " found in buffer `"
1375 << b->absFileName() << "'.");
1377 if (b == &buffer_) {
1381 dr.screenUpdate(Update::Force | Update::FitCursor);
1383 // Switch to other buffer view and resend cmd
1384 lyx::dispatch(FuncRequest(
1385 LFUN_BUFFER_SWITCH, b->absFileName()));
1393 case LFUN_NOTE_NEXT:
1394 gotoInset(this, NOTE_CODE, false);
1397 case LFUN_REFERENCE_NEXT: {
1398 vector<InsetCode> tmp;
1399 tmp.push_back(LABEL_CODE);
1400 tmp.push_back(REF_CODE);
1401 gotoInset(this, tmp, true);
1405 case LFUN_CHANGES_TRACK:
1406 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1409 case LFUN_CHANGES_OUTPUT:
1410 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1411 if (buffer_.params().outputChanges) {
1412 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1413 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1414 LaTeXFeatures::isAvailable("xcolor");
1416 if (!dvipost && !xcolorulem) {
1417 Alert::warning(_("Changes not shown in LaTeX output"),
1418 _("Changes will not be highlighted in LaTeX output, "
1419 "because neither dvipost nor xcolor/ulem are installed.\n"
1420 "Please install these packages or redefine "
1421 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1422 } else if (!xcolorulem) {
1423 Alert::warning(_("Changes not shown in LaTeX output"),
1424 _("Changes will not be highlighted in LaTeX output "
1425 "when using pdflatex, because xcolor and ulem are not installed.\n"
1426 "Please install both packages or redefine "
1427 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1432 case LFUN_CHANGE_NEXT:
1433 findNextChange(this);
1434 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1435 dr.screenUpdate(Update::Force | Update::FitCursor);
1438 case LFUN_CHANGE_PREVIOUS:
1439 findPreviousChange(this);
1440 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1441 dr.screenUpdate(Update::Force | Update::FitCursor);
1444 case LFUN_CHANGES_MERGE:
1445 if (findNextChange(this) || findPreviousChange(this)) {
1446 dr.screenUpdate(Update::Force | Update::FitCursor);
1447 dr.forceBufferUpdate();
1448 showDialog("changes");
1452 case LFUN_ALL_CHANGES_ACCEPT:
1453 // select complete document
1455 cur.selHandle(true);
1456 buffer_.text().cursorBottom(cur);
1457 // accept everything in a single step to support atomic undo
1458 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);
1474 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1475 dr.screenUpdate(Update::Force | Update::FitCursor);
1476 dr.forceBufferUpdate();
1479 case LFUN_WORD_FIND_FORWARD:
1480 case LFUN_WORD_FIND_BACKWARD: {
1481 static docstring last_search;
1482 docstring searched_string;
1484 if (!cmd.argument().empty()) {
1485 last_search = cmd.argument();
1486 searched_string = cmd.argument();
1488 searched_string = last_search;
1491 if (searched_string.empty())
1494 bool const fw = act == LFUN_WORD_FIND_FORWARD;
1495 docstring const data =
1496 find2string(searched_string, true, false, fw);
1497 bool found = lyxfind(this, FuncRequest(LFUN_WORD_FIND, data));
1499 dr.screenUpdate(Update::Force | Update::FitCursor);
1503 case LFUN_WORD_FIND: {
1504 FuncRequest req = cmd;
1505 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1506 req = d->search_request_cache_;
1507 if (req.argument().empty()) {
1508 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1511 if (lyxfind(this, req))
1512 dr.screenUpdate(Update::Force | Update::FitCursor);
1514 message(_("String not found!"));
1515 d->search_request_cache_ = req;
1519 case LFUN_WORD_REPLACE: {
1520 bool has_deleted = false;
1521 if (cur.selection()) {
1522 DocIterator beg = cur.selectionBegin();
1523 DocIterator end = cur.selectionEnd();
1524 if (beg.pit() == end.pit()) {
1525 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1526 if (!cur.inMathed() && cur.paragraph().isDeleted(p)) {
1533 if (lyxreplace(this, cmd, has_deleted)) {
1534 dr.forceBufferUpdate();
1535 dr.screenUpdate(Update::Force | Update::FitCursor);
1540 case LFUN_WORD_FINDADV: {
1541 FindAndReplaceOptions opt;
1542 istringstream iss(to_utf8(cmd.argument()));
1544 if (findAdv(this, opt)) {
1545 dr.screenUpdate(Update::Force | Update::FitCursor);
1556 cur.clearSelection();
1557 dr.setMessage(from_utf8(N_("Mark off")));
1561 cur.clearSelection();
1563 dr.setMessage(from_utf8(N_("Mark on")));
1566 case LFUN_MARK_TOGGLE:
1567 cur.setSelection(false);
1570 dr.setMessage(from_utf8(N_("Mark removed")));
1573 dr.setMessage(from_utf8(N_("Mark set")));
1578 case LFUN_SCREEN_SHOW_CURSOR:
1582 case LFUN_SCREEN_RECENTER:
1586 case LFUN_BIBTEX_DATABASE_ADD: {
1587 Cursor tmpcur = cur;
1588 findInset(tmpcur, BIBTEX_CODE, false);
1589 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1592 if (inset->addDatabase(cmd.argument())) {
1593 buffer_.invalidateBibfileCache();
1594 dr.forceBufferUpdate();
1600 case LFUN_BIBTEX_DATABASE_DEL: {
1601 Cursor tmpcur = cur;
1602 findInset(tmpcur, BIBTEX_CODE, false);
1603 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1606 if (inset->delDatabase(cmd.argument())) {
1607 buffer_.invalidateBibfileCache();
1608 dr.forceBufferUpdate();
1614 case LFUN_STATISTICS: {
1615 DocIterator from, to;
1616 if (cur.selection()) {
1617 from = cur.selectionBegin();
1618 to = cur.selectionEnd();
1620 from = doc_iterator_begin(&buffer_);
1621 to = doc_iterator_end(&buffer_);
1623 int const words = countWords(from, to);
1624 int const chars = countChars(from, to, false);
1625 int const chars_blanks = countChars(from, to, true);
1627 if (cur.selection())
1628 message = _("Statistics for the selection:");
1630 message = _("Statistics for the document:");
1633 message += bformat(_("%1$d words"), words);
1635 message += _("One word");
1637 if (chars_blanks != 1)
1638 message += bformat(_("%1$d characters (including blanks)"),
1641 message += _("One character (including blanks)");
1644 message += bformat(_("%1$d characters (excluding blanks)"),
1647 message += _("One character (excluding blanks)");
1649 Alert::information(_("Statistics"), message);
1653 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1654 // turn compression on/off
1655 buffer_.params().compressed = !buffer_.params().compressed;
1658 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
1659 buffer_.params().output_sync = !buffer_.params().output_sync;
1662 case LFUN_SCREEN_UP:
1663 case LFUN_SCREEN_DOWN: {
1664 Point p = getPos(cur);
1665 // This code has been commented out to enable to scroll down a
1666 // document, even if there are large insets in it (see bug #5465).
1667 /*if (p.y_ < 0 || p.y_ > height_) {
1668 // The cursor is off-screen so recenter before proceeding.
1672 int const scrolled = scroll(act == LFUN_SCREEN_UP
1673 ? -height_ : height_);
1674 if (act == LFUN_SCREEN_UP && scrolled > -height_)
1676 if (act == LFUN_SCREEN_DOWN && scrolled < height_)
1677 p = Point(width_, height_);
1679 bool const in_texted = cur.inTexted();
1681 buffer_.changed(true);
1682 updateHoveredInset();
1684 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1685 true, act == LFUN_SCREEN_UP);
1687 //FIXME: what to do with cur.x_target()?
1688 bool update = in_texted && cur.bv().checkDepm(cur, old);
1691 dr.screenUpdate(Update::Force | Update::FitCursor);
1692 dr.forceBufferUpdate();
1699 dr.forceBufferUpdate();
1702 case LFUN_SCREEN_UP_SELECT: {
1703 cur.selHandle(true);
1704 if (isTopScreen()) {
1705 lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1709 int y = getPos(cur).y_;
1710 int const ymin = y - height_ + defaultRowHeight();
1711 while (y > ymin && cur.up())
1715 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1719 case LFUN_SCREEN_DOWN_SELECT: {
1720 cur.selHandle(true);
1721 if (isBottomScreen()) {
1722 lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1726 int y = getPos(cur).y_;
1727 int const ymax = y + height_ - defaultRowHeight();
1728 while (y < ymax && cur.down())
1732 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1737 // This would be in Buffer class if only Cursor did not
1738 // require a bufferview
1739 case LFUN_INSET_FORALL: {
1740 docstring const name = from_utf8(cmd.getArg(0));
1741 string const commandstr = cmd.getLongArg(1);
1742 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
1744 // an arbitrary number to limit number of iterations
1745 const int max_iter = 10000;
1747 Cursor & cur = d->cursor_;
1748 Cursor const savecur = cur;
1750 if (!cur.nextInset())
1752 cur.beginUndoGroup();
1753 while(cur && iterations < max_iter) {
1754 Inset * ins = cur.nextInset();
1757 docstring insname = ins->layoutName();
1758 while (!insname.empty()) {
1759 if (insname == name || name == from_utf8("*")) {
1761 lyx::dispatch(fr, dr);
1765 size_t const i = insname.rfind(':');
1766 if (i == string::npos)
1768 insname = insname.substr(0, i);
1775 dr.screenUpdate(Update::Force);
1776 dr.forceBufferUpdate();
1778 if (iterations >= max_iter) {
1780 dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
1782 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
1787 case LFUN_BRANCH_ADD_INSERT: {
1788 docstring branch_name = from_utf8(cmd.getArg(0));
1789 if (branch_name.empty())
1790 if (!Alert::askForText(branch_name, _("Branch name")) ||
1791 branch_name.empty())
1794 DispatchResult drtmp;
1795 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
1796 if (drtmp.error()) {
1797 Alert::warning(_("Branch already exists"), drtmp.message());
1800 BranchList & branch_list = buffer_.params().branchlist();
1801 vector<docstring> const branches =
1802 getVectorFromString(branch_name, branch_list.separator());
1803 for (vector<docstring>::const_iterator it = branches.begin();
1804 it != branches.end(); ++it) {
1806 lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch_name));
1811 case LFUN_KEYMAP_OFF:
1812 getIntl().keyMapOn(false);
1815 case LFUN_KEYMAP_PRIMARY:
1816 getIntl().keyMapPrim();
1819 case LFUN_KEYMAP_SECONDARY:
1820 getIntl().keyMapSec();
1823 case LFUN_KEYMAP_TOGGLE:
1824 getIntl().toggleKeyMap();
1827 case LFUN_DIALOG_SHOW_NEW_INSET: {
1828 string const name = cmd.getArg(0);
1829 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1830 if (decodeInsetParam(name, data, buffer_))
1831 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1833 lyxerr << "Inset type '" << name <<
1834 "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" << endl;
1838 case LFUN_CITATION_INSERT: {
1839 if (argument.empty()) {
1840 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1843 // we can have one optional argument, delimited by '|'
1844 // citation-insert <key>|<text_before>
1845 // this should be enhanced to also support text_after
1846 // and citation style
1847 string arg = argument;
1849 if (contains(argument, "|")) {
1850 arg = token(argument, '|', 0);
1851 opt1 = token(argument, '|', 1);
1853 InsetCommandParams icp(CITE_CODE);
1854 icp["key"] = from_utf8(arg);
1856 icp["before"] = from_utf8(opt1);
1857 string icstr = InsetCommand::params2string(icp);
1858 FuncRequest fr(LFUN_INSET_INSERT, icstr);
1863 case LFUN_INSET_APPLY: {
1864 string const name = cmd.getArg(0);
1865 Inset * inset = editedInset(name);
1867 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1871 // put cursor in front of inset.
1872 if (!setCursorFromInset(inset)) {
1873 LASSERT(false, break);
1876 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1877 inset->dispatch(cur, fr);
1878 dr.screenUpdate(cur.result().screenUpdate());
1879 if (cur.result().needBufferUpdate())
1880 dr.forceBufferUpdate();
1885 // OK, so try the Buffer itself...
1886 buffer_.dispatch(cmd, dr);
1887 dispatched = dr.dispatched();
1891 buffer_.undo().endUndoGroup();
1892 dr.dispatched(dispatched);
1896 docstring const BufferView::requestSelection()
1898 Cursor & cur = d->cursor_;
1900 LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
1901 if (!cur.selection()) {
1902 d->xsel_cache_.set = false;
1906 LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
1907 if (!d->xsel_cache_.set ||
1908 cur.top() != d->xsel_cache_.cursor ||
1909 cur.realAnchor().top() != d->xsel_cache_.anchor)
1911 d->xsel_cache_.cursor = cur.top();
1912 d->xsel_cache_.anchor = cur.realAnchor().top();
1913 d->xsel_cache_.set = cur.selection();
1914 return cur.selectionAsString(false);
1920 void BufferView::clearSelection()
1922 d->cursor_.clearSelection();
1923 // Clear the selection buffer. Otherwise a subsequent
1924 // middle-mouse-button paste would use the selection buffer,
1925 // not the more current external selection.
1926 cap::clearSelection();
1927 d->xsel_cache_.set = false;
1928 // The buffer did not really change, but this causes the
1929 // redraw we need because we cleared the selection above.
1930 buffer_.changed(false);
1934 void BufferView::resize(int width, int height)
1936 // Update from work area
1940 // Clear the paragraph height cache.
1941 d->par_height_.clear();
1942 // Redo the metrics.
1947 Inset const * BufferView::getCoveringInset(Text const & text,
1950 TextMetrics & tm = d->text_metrics_[&text];
1951 Inset * inset = tm.checkInsetHit(x, y);
1955 if (!inset->descendable(*this))
1956 // No need to go further down if the inset is not
1960 size_t cell_number = inset->nargs();
1961 // Check all the inner cell.
1962 for (size_t i = 0; i != cell_number; ++i) {
1963 Text const * inner_text = inset->getText(i);
1966 Inset const * inset_deeper =
1967 getCoveringInset(*inner_text, x, y);
1969 return inset_deeper;
1977 void BufferView::updateHoveredInset() const
1979 // Get inset under mouse, if there is one.
1980 int const x = d->mouse_position_cache_.x_;
1981 int const y = d->mouse_position_cache_.y_;
1982 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
1984 d->clickable_inset_ = covering_inset && covering_inset->clickable(x, y);
1986 if (covering_inset == d->last_inset_)
1987 // Same inset, no need to do anything...
1990 bool need_redraw = false;
1991 if (d->last_inset_) {
1992 // Remove the hint on the last hovered inset (if any).
1993 need_redraw |= d->last_inset_->setMouseHover(this, false);
1997 if (covering_inset && covering_inset->setMouseHover(this, true)) {
1999 // Only the insets that accept the hover state, do
2000 // clear the last_inset_, so only set the last_inset_
2001 // member if the hovered setting is accepted.
2002 d->last_inset_ = covering_inset;
2006 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
2007 << d->mouse_position_cache_.x_ << ", "
2008 << d->mouse_position_cache_.y_ << ")");
2010 d->update_strategy_ = DecorationUpdate;
2012 // This event (moving without mouse click) is not passed further.
2013 // This should be changed if it is further utilized.
2014 buffer_.changed(false);
2019 void BufferView::clearLastInset(Inset * inset) const
2021 if (d->last_inset_ != inset) {
2022 LYXERR0("Wrong last_inset!");
2023 LASSERT(false, /**/);
2029 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
2031 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
2033 // This is only called for mouse related events including
2034 // LFUN_FILE_OPEN generated by drag-and-drop.
2035 FuncRequest cmd = cmd0;
2037 Cursor old = cursor();
2039 cur.push(buffer_.inset());
2040 cur.setSelection(d->cursor_.selection());
2042 // Either the inset under the cursor or the
2043 // surrounding Text will handle this event.
2045 // make sure we stay within the screen...
2046 cmd.set_y(min(max(cmd.y(), -1), height_));
2048 d->mouse_position_cache_.x_ = cmd.x();
2049 d->mouse_position_cache_.y_ = cmd.y();
2051 if (cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
2052 updateHoveredInset();
2056 // Build temporary cursor.
2057 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x(), cmd.y());
2059 // Put anchor at the same position.
2062 cur.beginUndoGroup();
2064 // Try to dispatch to an non-editable inset near this position
2065 // via the temp cursor. If the inset wishes to change the real
2066 // cursor it has to do so explicitly by using
2067 // cur.bv().cursor() = cur; (or similar)
2069 inset->dispatch(cur, cmd);
2071 // Now dispatch to the temporary cursor. If the real cursor should
2072 // be modified, the inset's dispatch has to do so explicitly.
2073 if (!inset || !cur.result().dispatched())
2078 // Notify left insets
2081 bool badcursor = notifyCursorLeavesOrEnters(old, cur);
2083 cursor().fixIfBroken();
2086 // Do we have a selection?
2087 theSelection().haveSelection(cursor().selection());
2089 if (cur.needBufferUpdate()) {
2090 cur.clearBufferUpdate();
2091 buffer().updateBuffer();
2094 // If the command has been dispatched,
2095 if (cur.result().dispatched() || cur.result().screenUpdate())
2096 processUpdateFlags(cur.result().screenUpdate());
2100 void BufferView::lfunScroll(FuncRequest const & cmd)
2102 string const scroll_type = cmd.getArg(0);
2103 int scroll_step = 0;
2104 if (scroll_type == "line")
2105 scroll_step = d->scrollbarParameters_.single_step;
2106 else if (scroll_type == "page")
2107 scroll_step = d->scrollbarParameters_.page_step;
2110 string const scroll_quantity = cmd.getArg(1);
2111 if (scroll_quantity == "up")
2112 scrollUp(scroll_step);
2113 else if (scroll_quantity == "down")
2114 scrollDown(scroll_step);
2116 int const scroll_value = convert<int>(scroll_quantity);
2118 scroll(scroll_step * scroll_value);
2120 buffer_.changed(true);
2121 updateHoveredInset();
2125 int BufferView::minVisiblePart()
2127 return 2 * defaultRowHeight();
2131 int BufferView::scroll(int y)
2134 return scrollDown(y);
2136 return scrollUp(-y);
2141 int BufferView::scrollDown(int offset)
2143 Text * text = &buffer_.text();
2144 TextMetrics & tm = d->text_metrics_[text];
2145 int const ymax = height_ + offset;
2147 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2148 int bottom_pos = last.second->position() + last.second->descent();
2149 if (lyxrc.scroll_below_document)
2150 bottom_pos += height_ - minVisiblePart();
2151 if (last.first + 1 == int(text->paragraphs().size())) {
2152 if (bottom_pos <= height_)
2154 offset = min(offset, bottom_pos - height_);
2157 if (bottom_pos > ymax)
2159 tm.newParMetricsDown();
2161 d->anchor_ypos_ -= offset;
2166 int BufferView::scrollUp(int offset)
2168 Text * text = &buffer_.text();
2169 TextMetrics & tm = d->text_metrics_[text];
2170 int ymin = - offset;
2172 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2173 int top_pos = first.second->position() - first.second->ascent();
2174 if (first.first == 0) {
2177 offset = min(offset, - top_pos);
2182 tm.newParMetricsUp();
2184 d->anchor_ypos_ += offset;
2189 void BufferView::setCursorFromRow(int row)
2194 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
2198 buffer_.text().setCursor(d->cursor_, 0, 0);
2200 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
2201 d->cursor_.setSelection(false);
2202 d->cursor_.resetAnchor();
2207 bool BufferView::setCursorFromInset(Inset const * inset)
2209 // are we already there?
2210 if (cursor().nextInset() == inset)
2213 // Inset is not at cursor position. Find it in the document.
2216 while (cur && cur.nextInset() != inset)
2227 void BufferView::gotoLabel(docstring const & label)
2229 ListOfBuffers bufs = buffer().allRelatives();
2230 ListOfBuffers::iterator it = bufs.begin();
2231 for (; it != bufs.end(); ++it) {
2232 Buffer const * buf = *it;
2235 Toc & toc = buf->tocBackend().toc("label");
2236 TocIterator toc_it = toc.begin();
2237 TocIterator end = toc.end();
2238 for (; toc_it != end; ++toc_it) {
2239 if (label == toc_it->str()) {
2240 lyx::dispatch(toc_it->action());
2248 TextMetrics const & BufferView::textMetrics(Text const * t) const
2250 return const_cast<BufferView *>(this)->textMetrics(t);
2254 TextMetrics & BufferView::textMetrics(Text const * t)
2257 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
2258 if (tmc_it == d->text_metrics_.end()) {
2259 tmc_it = d->text_metrics_.insert(
2260 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
2262 return tmc_it->second;
2266 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2269 return textMetrics(t).parMetrics(pit);
2273 int BufferView::workHeight() const
2279 void BufferView::setCursor(DocIterator const & dit)
2282 size_t const n = dit.depth();
2283 for (size_t i = 0; i < n; ++i)
2284 dit[i].inset().edit(d->cursor_, true);
2286 d->cursor_.setCursor(dit);
2287 d->cursor_.setSelection(false);
2289 // It seems on general grounds as if this is probably needed, but
2290 // it is not yet clear.
2291 // See bug #7394 and r38388.
2292 // d->cursor.resetAnchor();
2296 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2298 // Would be wrong to delete anything if we have a selection.
2299 if (cur.selection())
2302 bool need_anchor_change = false;
2303 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
2304 need_anchor_change);
2306 if (need_anchor_change)
2314 cur.forceBufferUpdate();
2315 buffer_.changed(true);
2320 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
2322 LASSERT(&cur.bv() == this, /**/);
2325 // this event will clear selection so we save selection for
2326 // persistent selection
2327 cap::saveSelection(cursor());
2329 d->cursor_.macroModeClose();
2331 // Has the cursor just left the inset?
2332 bool const leftinset = (&d->cursor_.inset() != &cur.inset());
2334 d->cursor_.fixIfBroken();
2336 // FIXME: shift-mouse selection doesn't work well across insets.
2337 bool const do_selection =
2338 select && &d->cursor_.normalAnchor().inset() == &cur.inset();
2340 // do the dEPM magic if needed
2341 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2342 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2343 // the leftinset bool would not be necessary (badcursor instead).
2344 bool update = leftinset;
2345 if (!do_selection && d->cursor_.inTexted())
2346 update |= checkDepm(cur, d->cursor_);
2349 d->cursor_.resetAnchor();
2350 d->cursor_.setCursor(cur);
2351 d->cursor_.boundary(cur.boundary());
2353 d->cursor_.setSelection();
2355 d->cursor_.clearSelection();
2357 d->cursor_.finishUndo();
2358 d->cursor_.setCurrentFont();
2360 cur.forceBufferUpdate();
2365 void BufferView::putSelectionAt(DocIterator const & cur,
2366 int length, bool backwards)
2368 d->cursor_.clearSelection();
2374 d->cursor_.pos() += length;
2375 d->cursor_.setSelection(d->cursor_, -length);
2377 d->cursor_.setSelection(d->cursor_, length);
2382 bool BufferView::selectIfEmpty(DocIterator & cur)
2384 if (!cur.paragraph().empty())
2387 pit_type const beg_pit = cur.pit();
2389 // The paragraph associated to this item isn't
2390 // the first one, so it can be selected
2393 // We have to resort to select the space between the
2394 // end of this item and the begin of the next one
2398 // If it is the only item in the document,
2399 // nothing can be selected
2402 pit_type const end_pit = cur.pit();
2403 pos_type const end_pos = cur.pos();
2404 d->cursor_.clearSelection();
2406 d->cursor_.setCursor(cur);
2407 d->cursor_.pit() = beg_pit;
2408 d->cursor_.pos() = 0;
2409 d->cursor_.setSelection(false);
2410 d->cursor_.resetAnchor();
2411 d->cursor_.pit() = end_pit;
2412 d->cursor_.pos() = end_pos;
2413 d->cursor_.setSelection();
2418 Cursor & BufferView::cursor()
2424 Cursor const & BufferView::cursor() const
2430 pit_type BufferView::anchor_ref() const
2432 return d->anchor_pit_;
2436 bool BufferView::singleParUpdate()
2438 Text & buftext = buffer_.text();
2439 pit_type const bottom_pit = d->cursor_.bottom().pit();
2440 TextMetrics & tm = textMetrics(&buftext);
2441 int old_height = tm.parMetrics(bottom_pit).height();
2443 // make sure inline completion pointer is ok
2444 if (d->inlineCompletionPos_.fixIfBroken())
2445 d->inlineCompletionPos_ = DocIterator();
2447 // In Single Paragraph mode, rebreak only
2448 // the (main text, not inset!) paragraph containing the cursor.
2449 // (if this paragraph contains insets etc., rebreaking will
2450 // recursively descend)
2451 tm.redoParagraph(bottom_pit);
2452 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
2453 if (pm.height() != old_height)
2454 // Paragraph height has changed so we cannot proceed to
2455 // the singlePar optimisation.
2458 d->update_strategy_ = SingleParUpdate;
2460 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2461 << " y2: " << pm.position() + pm.descent()
2462 << " pit: " << bottom_pit
2463 << " singlepar: 1");
2468 void BufferView::updateMetrics()
2470 if (height_ == 0 || width_ == 0)
2473 Text & buftext = buffer_.text();
2474 pit_type const npit = int(buftext.paragraphs().size());
2476 // Clear out the position cache in case of full screen redraw,
2477 d->coord_cache_.clear();
2479 // Clear out paragraph metrics to avoid having invalid metrics
2480 // in the cache from paragraphs not relayouted below
2481 // The complete text metrics will be redone.
2482 d->text_metrics_.clear();
2484 TextMetrics & tm = textMetrics(&buftext);
2486 // make sure inline completion pointer is ok
2487 if (d->inlineCompletionPos_.fixIfBroken())
2488 d->inlineCompletionPos_ = DocIterator();
2490 if (d->anchor_pit_ >= npit)
2491 // The anchor pit must have been deleted...
2492 d->anchor_pit_ = npit - 1;
2494 // Rebreak anchor paragraph.
2495 tm.redoParagraph(d->anchor_pit_);
2496 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2499 if (d->anchor_pit_ == 0) {
2500 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2502 // Complete buffer visible? Then it's easy.
2503 if (scrollRange == 0)
2504 d->anchor_ypos_ = anchor_pm.ascent();
2506 // FIXME: Some clever handling needed to show
2507 // the _first_ paragraph up to the top if the cursor is
2508 // in the first line.
2510 anchor_pm.setPosition(d->anchor_ypos_);
2512 LYXERR(Debug::PAINTING, "metrics: "
2513 << " anchor pit = " << d->anchor_pit_
2514 << " anchor ypos = " << d->anchor_ypos_);
2516 // Redo paragraphs above anchor if necessary.
2517 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2518 // We are now just above the anchor paragraph.
2519 pit_type pit1 = d->anchor_pit_ - 1;
2520 for (; pit1 >= 0 && y1 >= 0; --pit1) {
2521 tm.redoParagraph(pit1);
2522 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2524 // Save the paragraph position in the cache.
2529 // Redo paragraphs below the anchor if necessary.
2530 int y2 = d->anchor_ypos_ + anchor_pm.descent();
2531 // We are now just below the anchor paragraph.
2532 pit_type pit2 = d->anchor_pit_ + 1;
2533 for (; pit2 < npit && y2 <= height_; ++pit2) {
2534 tm.redoParagraph(pit2);
2535 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2537 // Save the paragraph position in the cache.
2542 LYXERR(Debug::PAINTING, "Metrics: "
2543 << " anchor pit = " << d->anchor_pit_
2544 << " anchor ypos = " << d->anchor_ypos_
2547 << " pit1 = " << pit1
2548 << " pit2 = " << pit2);
2550 d->update_strategy_ = FullScreenUpdate;
2552 if (lyxerr.debugging(Debug::WORKAREA)) {
2553 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2554 d->coord_cache_.dump();
2559 void BufferView::insertLyXFile(FileName const & fname)
2561 LASSERT(d->cursor_.inTexted(), /**/);
2563 // Get absolute path of file and add ".lyx"
2564 // to the filename if necessary
2565 FileName filename = fileSearch(string(), fname.absFileName(), "lyx");
2567 docstring const disp_fn = makeDisplayPath(filename.absFileName());
2568 // emit message signal.
2569 message(bformat(_("Inserting document %1$s..."), disp_fn));
2572 Buffer buf(filename.absFileName(), false);
2573 if (buf.loadLyXFile() == Buffer::ReadSuccess) {
2574 ErrorList & el = buffer_.errorList("Parse");
2575 // Copy the inserted document error list into the current buffer one.
2576 el = buf.errorList("Parse");
2577 buffer_.undo().recordUndo(d->cursor_);
2578 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2579 buf.params().documentClassPtr(), el);
2580 res = _("Document %1$s inserted.");
2582 res = _("Could not insert document %1$s");
2585 buffer_.changed(true);
2586 // emit message signal.
2587 message(bformat(res, disp_fn));
2591 Point BufferView::coordOffset(DocIterator const & dit) const
2597 // Addup contribution of nested insets, from inside to outside,
2598 // keeping the outer paragraph for a special handling below
2599 for (size_t i = dit.depth() - 1; i >= 1; --i) {
2600 CursorSlice const & sl = dit[i];
2604 // get relative position inside sl.inset()
2605 sl.inset().cursorPos(*this, sl, dit.boundary() && (i + 1 == dit.depth()), xx, yy);
2607 // Make relative position inside of the edited inset relative to sl.inset()
2611 // In case of an RTL inset, the edited inset will be positioned to the left
2614 bool boundary_i = dit.boundary() && i + 1 == dit.depth();
2615 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2620 // remember width for the case that sl.inset() is positioned in an RTL inset
2621 if (i && dit[i - 1].text()) {
2622 // If this Inset is inside a Text Inset, retrieve the Dimension
2623 // from the containing text instead of using Inset::dimension() which
2624 // might not be implemented.
2625 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2626 // elimination of Inset::dim_ cache. This coordOffset() method needs
2627 // to be rewritten in light of the new design.
2628 Dimension const & dim = parMetrics(dit[i - 1].text(),
2629 dit[i - 1].pit()).insetDimension(&sl.inset());
2632 Dimension const dim = sl.inset().dimension(*this);
2636 //lyxerr << "Cursor::getPos, i: "
2637 // << i << " x: " << xx << " y: " << y << endl;
2640 // Add contribution of initial rows of outermost paragraph
2641 CursorSlice const & sl = dit[0];
2642 TextMetrics const & tm = textMetrics(sl.text());
2643 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2644 LASSERT(!pm.rows().empty(), /**/);
2645 y -= pm.rows()[0].ascent();
2647 // FIXME: document this mess
2649 if (sl.pos() > 0 && dit.depth() == 1) {
2651 if (pos && dit.boundary())
2653 // lyxerr << "coordOffset: boundary:" << dit.boundary() << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2654 rend = pm.pos2row(pos);
2656 rend = pm.pos2row(sl.pos());
2658 size_t rend = pm.pos2row(sl.pos());
2660 for (size_t rit = 0; rit != rend; ++rit)
2661 y += pm.rows()[rit].height();
2662 y += pm.rows()[rend].ascent();
2664 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2666 // Make relative position from the nested inset now bufferview absolute.
2667 int xx = bottom_tm.cursorX(dit.bottom(), dit.boundary() && dit.depth() == 1);
2670 // In the RTL case place the nested inset at the left of the cursor in
2671 // the outer paragraph
2672 bool boundary_1 = dit.boundary() && 1 == dit.depth();
2673 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2681 Point BufferView::getPos(DocIterator const & dit) const
2683 if (!paragraphVisible(dit))
2684 return Point(-1, -1);
2686 CursorSlice const & bot = dit.bottom();
2687 TextMetrics const & tm = textMetrics(bot.text());
2689 // offset from outer paragraph
2690 Point p = coordOffset(dit);
2691 p.y_ += tm.parMetrics(bot.pit()).position();
2696 bool BufferView::paragraphVisible(DocIterator const & dit) const
2698 CursorSlice const & bot = dit.bottom();
2699 TextMetrics const & tm = textMetrics(bot.text());
2701 return tm.contains(bot.pit());
2705 void BufferView::cursorPosAndHeight(Point & p, int & h) const
2707 Cursor const & cur = cursor();
2708 Font const font = cur.getFont();
2709 frontend::FontMetrics const & fm = theFontMetrics(font);
2710 int const asc = fm.maxAscent();
2711 int const des = fm.maxDescent();
2718 bool BufferView::cursorInView(Point const & p, int h) const
2720 Cursor const & cur = cursor();
2721 // does the cursor touch the screen ?
2722 if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
2728 void BufferView::draw(frontend::Painter & pain)
2730 if (height_ == 0 || width_ == 0)
2732 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
2734 Text & text = buffer_.text();
2735 TextMetrics const & tm = d->text_metrics_[&text];
2736 int const y = tm.first().second->position();
2737 PainterInfo pi(this, pain);
2739 switch (d->update_strategy_) {
2741 case NoScreenUpdate:
2742 // If no screen painting is actually needed, only some the different
2743 // coordinates of insets and paragraphs needs to be updated.
2744 pi.full_repaint = true;
2745 pi.pain.setDrawingEnabled(false);
2749 case SingleParUpdate:
2750 pi.full_repaint = false;
2751 // In general, only the current row of the outermost paragraph
2752 // will be redrawn. Particular cases where selection spans
2753 // multiple paragraph are correctly detected in TextMetrics.
2757 case DecorationUpdate:
2758 // FIXME: We should also distinguish DecorationUpdate to avoid text
2759 // drawing if possible. This is not possible to do easily right now
2760 // because of the single backing pixmap.
2762 case FullScreenUpdate:
2763 // The whole screen, including insets, will be refreshed.
2764 pi.full_repaint = true;
2766 // Clear background.
2767 pain.fillRectangle(0, 0, width_, height_,
2768 pi.backgroundColor(&buffer_.inset()));
2773 // and possibly grey out below
2774 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2775 int const y2 = lastpm.second->position() + lastpm.second->descent();
2778 Color color = buffer().isInternal()
2779 ? Color_background : Color_bottomarea;
2780 pain.fillRectangle(0, y2, width_, height_ - y2, color);
2784 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
2786 // The scrollbar needs an update.
2789 // Normalize anchor for next time
2790 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2791 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2792 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2793 ParagraphMetrics const & pm = tm.parMetrics(pit);
2794 if (pm.position() + pm.descent() > 0) {
2795 d->anchor_pit_ = pit;
2796 d->anchor_ypos_ = pm.position();
2800 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2801 << " anchor ypos = " << d->anchor_ypos_);
2805 void BufferView::message(docstring const & msg)
2808 d->gui_->message(msg);
2812 void BufferView::showDialog(string const & name)
2815 d->gui_->showDialog(name, string());
2819 void BufferView::showDialog(string const & name,
2820 string const & data, Inset * inset)
2823 d->gui_->showDialog(name, data, inset);
2827 void BufferView::updateDialog(string const & name, string const & data)
2830 d->gui_->updateDialog(name, data);
2834 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2840 // FIXME: Move this out of BufferView again
2841 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2843 if (!fname.isReadableFile()) {
2844 docstring const error = from_ascii(strerror(errno));
2845 docstring const file = makeDisplayPath(fname.absFileName(), 50);
2846 docstring const text =
2847 bformat(_("Could not read the specified document\n"
2848 "%1$s\ndue to the error: %2$s"), file, error);
2849 Alert::error(_("Could not read file"), text);
2853 if (!fname.isReadableFile()) {
2854 docstring const file = makeDisplayPath(fname.absFileName(), 50);
2855 docstring const text =
2856 bformat(_("%1$s\n is not readable."), file);
2857 Alert::error(_("Could not open file"), text);
2861 // FIXME UNICODE: We don't know the encoding of the file
2862 docstring file_content = fname.fileContents("UTF-8");
2863 if (file_content.empty()) {
2864 Alert::error(_("Reading not UTF-8 encoded file"),
2865 _("The file is not UTF-8 encoded.\n"
2866 "It will be read as local 8Bit-encoded.\n"
2867 "If this does not give the correct result\n"
2868 "then please change the encoding of the file\n"
2869 "to UTF-8 with a program other than LyX.\n"));
2870 file_content = fname.fileContents("local8bit");
2873 return normalize_c(file_content);
2877 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2879 docstring const tmpstr = contentsOfPlaintextFile(f);
2884 Cursor & cur = cursor();
2885 cap::replaceSelection(cur);
2886 buffer_.undo().recordUndo(cur);
2888 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
2890 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
2892 buffer_.changed(true);
2896 docstring const & BufferView::inlineCompletion() const
2898 return d->inlineCompletion_;
2902 size_t const & BufferView::inlineCompletionUniqueChars() const
2904 return d->inlineCompletionUniqueChars_;
2908 DocIterator const & BufferView::inlineCompletionPos() const
2910 return d->inlineCompletionPos_;
2914 void BufferView::resetInlineCompletionPos()
2916 d->inlineCompletionPos_ = DocIterator();
2920 bool samePar(DocIterator const & a, DocIterator const & b)
2922 if (a.empty() && b.empty())
2924 if (a.empty() || b.empty())
2926 if (a.depth() != b.depth())
2928 return &a.innerParagraph() == &b.innerParagraph();
2932 void BufferView::setInlineCompletion(Cursor & cur, DocIterator const & pos,
2933 docstring const & completion, size_t uniqueChars)
2935 uniqueChars = min(completion.size(), uniqueChars);
2936 bool changed = d->inlineCompletion_ != completion
2937 || d->inlineCompletionUniqueChars_ != uniqueChars;
2938 bool singlePar = true;
2939 d->inlineCompletion_ = completion;
2940 d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
2942 //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
2945 DocIterator const & old = d->inlineCompletionPos_;
2947 //lyxerr << "inlineCompletionPos changed" << std::endl;
2948 // old or pos are in another paragraph?
2949 if ((!samePar(cur, pos) && !pos.empty())
2950 || (!samePar(cur, old) && !old.empty())) {
2952 //lyxerr << "different paragraph" << std::endl;
2954 d->inlineCompletionPos_ = pos;
2959 if (singlePar && !(cur.result().screenUpdate() & Update::Force))
2960 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
2962 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::Force);
2967 bool BufferView::clickableInset() const
2969 return d->clickable_inset_;