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"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "callback.h" // added for Dispatch functions
24 #include "CoordCache.h"
25 #include "CutAndPaste.h"
27 #include "DispatchResult.h"
28 #include "ErrorList.h"
30 #include "FloatList.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
35 #include "InsetIterator.h"
37 #include "LaTeXFeatures.h"
43 #include "MetricsInfo.h"
44 #include "Paragraph.h"
45 #include "paragraph_funcs.h"
46 #include "ParagraphParameters.h"
47 #include "ParIterator.h"
51 #include "TextClass.h"
54 #include "WordLangTuple.h"
56 #include "insets/InsetBibtex.h"
57 #include "insets/InsetCommand.h" // ChangeRefs
58 #include "insets/InsetRef.h"
59 #include "insets/InsetText.h"
61 #include "frontends/alert.h"
62 #include "frontends/FileDialog.h"
63 #include "frontends/FontMetrics.h"
64 #include "frontends/Painter.h"
65 #include "frontends/Selection.h"
67 #include "graphics/Previews.h"
69 #include "support/convert.h"
70 #include "support/FileFilterList.h"
71 #include "support/filetools.h"
72 #include "support/Package.h"
73 #include "support/types.h"
75 #include <boost/bind.hpp>
76 #include <boost/current_function.hpp>
83 using std::istringstream;
87 using std::mem_fun_ref;
94 using support::addPath;
95 using support::bformat;
96 using support::FileFilterList;
97 using support::FileName;
98 using support::fileSearch;
99 using support::isDirWriteable;
100 using support::isFileReadable;
101 using support::makeDisplayPath;
102 using support::package;
104 namespace Alert = frontend::Alert;
108 /// Return an inset of this class if it exists at the current cursor position
110 T * getInsetByCode(Cursor const & cur, Inset::Code code)
112 DocIterator it = cur;
113 Inset * inset = it.nextInset();
114 if (inset && inset->lyxCode() == code)
115 return static_cast<T*>(inset);
120 bool findInset(DocIterator & dit, vector<Inset_code> const & codes,
123 bool findNextInset(DocIterator & dit, vector<Inset_code> const & codes,
124 string const & contents)
126 DocIterator tmpdit = dit;
129 Inset const * inset = tmpdit.nextInset();
131 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
132 && (contents.empty() ||
133 static_cast<InsetCommand const *>(inset)->getContents() == contents)) {
137 tmpdit.forwardInset();
144 /// Looks for next inset with one of the the given code
145 bool findInset(DocIterator & dit, vector<Inset_code> const & codes,
149 DocIterator tmpdit = dit;
150 tmpdit.forwardInset();
155 Inset const * inset = tmpdit.nextInset();
157 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
158 contents = static_cast<InsetCommand const *>(inset)->getContents();
162 if (!findNextInset(tmpdit, codes, contents)) {
163 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
164 tmpdit = doc_iterator_begin(tmpdit.bottom().inset());
165 if (!findNextInset(tmpdit, codes, contents))
176 /// Looks for next inset with the given code
177 void findInset(DocIterator & dit, Inset_code code, bool same_content)
179 findInset(dit, vector<Inset_code>(1, code), same_content);
183 /// Moves cursor to the next inset with one of the given codes.
184 void gotoInset(BufferView * bv, vector<Inset_code> const & codes,
187 Cursor tmpcur = bv->cursor();
188 if (!findInset(tmpcur, codes, same_content)) {
189 bv->cursor().message(_("No more insets"));
193 tmpcur.clearSelection();
194 bv->setCursor(tmpcur);
198 /// Moves cursor to the next inset with given code.
199 void gotoInset(BufferView * bv, Inset_code code, bool same_content)
201 gotoInset(bv, vector<Inset_code>(1, code), same_content);
206 /// the type of outline operation
208 OutlineUp, // Move this header with text down
209 OutlineDown, // Move this header with text up
210 OutlineIn, // Make this header deeper
211 OutlineOut // Make this header shallower
215 void outline(OutlineOp mode, Cursor & cur)
217 Buffer & buf = cur.buffer();
218 pit_type & pit = cur.pit();
219 ParagraphList & pars = buf.text().paragraphs();
220 ParagraphList::iterator bgn = pars.begin();
221 // The first paragraph of the area to be copied:
222 ParagraphList::iterator start = boost::next(bgn, pit);
223 // The final paragraph of area to be copied:
224 ParagraphList::iterator finish = start;
225 ParagraphList::iterator end = pars.end();
227 TextClass::const_iterator lit =
228 buf.params().getTextClass().begin();
229 TextClass::const_iterator const lend =
230 buf.params().getTextClass().end();
232 int const thistoclevel = start->layout()->toclevel;
236 // Move out (down) from this section header
239 // Seek the one (on same level) below
240 for (; finish != end; ++finish) {
241 toclevel = finish->layout()->toclevel;
242 if (toclevel != Layout::NOT_IN_TOC
243 && toclevel <= thistoclevel) {
247 ParagraphList::iterator dest = start;
248 // Move out (up) from this header
251 // Search previous same-level header above
254 toclevel = dest->layout()->toclevel;
256 && (toclevel == Layout::NOT_IN_TOC
257 || toclevel > thistoclevel));
258 // Not found; do nothing
259 if (toclevel == Layout::NOT_IN_TOC || toclevel > thistoclevel)
261 pit_type const newpit = std::distance(bgn, dest);
262 pit_type const len = std::distance(start, finish);
263 pit_type const deletepit = pit + len;
264 recordUndo(cur, Undo::ATOMIC, newpit, deletepit - 1);
265 pars.insert(dest, start, finish);
266 start = boost::next(pars.begin(), deletepit);
268 pars.erase(start, finish);
272 // Go down out of current header:
275 // Find next same-level header:
276 for (; finish != end; ++finish) {
277 toclevel = finish->layout()->toclevel;
278 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
281 ParagraphList::iterator dest = finish;
282 // Go one down from *this* header:
287 // Go further down to find header to insert in front of:
288 for (; dest != end; ++dest) {
289 toclevel = dest->layout()->toclevel;
290 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
293 // One such was found:
294 pit_type newpit = std::distance(bgn, dest);
295 pit_type const len = std::distance(start, finish);
296 recordUndo(cur, Undo::ATOMIC, pit, newpit - 1);
297 pars.insert(dest, start, finish);
298 start = boost::next(bgn, pit);
300 pars.erase(start, finish);
305 for (; lit != lend; ++lit) {
306 if ((*lit)->toclevel == thistoclevel + 1 &&
307 start->layout()->labeltype == (*lit)->labeltype) {
308 start->layout((*lit));
315 for (; lit != lend; ++lit) {
316 if ((*lit)->toclevel == thistoclevel - 1 &&
317 start->layout()->labeltype == (*lit)->labeltype) {
318 start->layout((*lit));
331 /////////////////////////////////////////////////////////////////////
335 /////////////////////////////////////////////////////////////////////
338 BufferView::BufferView(Buffer & buf)
339 : width_(0), height_(0), buffer_(buf), wh_(0),
341 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
342 need_centering_(false), intl_(new Intl), last_inset_(0)
344 xsel_cache_.set = false;
345 intl_->initKeyMapper(lyxrc.use_kbmap);
347 cursor_.push(buffer_.inset());
348 cursor_.resetAnchor();
349 cursor_.setCurrentFont();
351 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
352 graphics::Previews::get().generateBufferPreviews(buffer_);
356 BufferView::~BufferView()
358 // current buffer is going to be switched-off, save cursor pos
359 // Ideally, the whole cursor stack should be saved, but session
360 // currently can only handle bottom (whole document) level pit and pos.
361 // That is to say, if a cursor is in a nested inset, it will be
362 // restore to the left of the top level inset.
363 LyX::ref().session().lastFilePos().save(
364 support::FileName(buffer_.fileName()),
365 boost::tie(cursor_.bottom().pit(), cursor_.bottom().pos()) );
369 Buffer & BufferView::buffer()
375 Buffer const & BufferView::buffer() const
381 bool BufferView::fitCursor()
383 if (cursorStatus(cursor_) == CUR_INSIDE) {
384 frontend::FontMetrics const & fm =
385 theFontMetrics(cursor_.getFont());
386 int const asc = fm.maxAscent();
387 int const des = fm.maxDescent();
388 Point const p = getPos(cursor_, cursor_.boundary());
389 if (p.y_ - asc >= 0 && p.y_ + des < height_)
397 bool BufferView::multiParSel()
399 if (!cursor_.selection())
401 bool ret = multiparsel_cache_;
402 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
403 // Either this, or previous selection spans paragraphs
404 return ret || multiparsel_cache_;
408 bool BufferView::update(Update::flags flags)
410 // last_inset_ points to the last visited inset. This pointer may become
411 // invalid because of keyboard editing. Since all such operations
412 // causes screen update(), I reset last_inset_ to avoid such a problem.
414 // This is close to a hot-path.
416 << BOOST_CURRENT_FUNCTION
417 << "[fitcursor = " << (flags & Update::FitCursor)
418 << ", forceupdate = " << (flags & Update::Force)
419 << ", singlepar = " << (flags & Update::SinglePar)
420 << "] buffer: " << &buffer_ << endl;
422 // Update macro store
423 if (!(cursor().inMathed() && cursor().inMacroMode()))
424 buffer_.buildMacros();
426 // Now do the first drawing step if needed. This consists on updating
427 // the CoordCache in updateMetrics().
428 // The second drawing step is done in WorkArea::redraw() if needed.
430 // Case when no explicit update is requested.
432 // no need to redraw anything.
433 metrics_info_.update_strategy = NoScreenUpdate;
437 if (flags == Update::Decoration) {
438 metrics_info_.update_strategy = DecorationUpdate;
442 if (flags == Update::FitCursor
443 || flags == (Update::Decoration | Update::FitCursor)) {
444 bool const fit_cursor = fitCursor();
445 // tell the frontend to update the screen if needed.
447 updateMetrics(false);
450 if (flags & Update::Decoration) {
451 metrics_info_.update_strategy = DecorationUpdate;
454 // no screen update is needed.
455 metrics_info_.update_strategy = NoScreenUpdate;
459 bool full_metrics = flags & Update::Force;
460 if (flags & Update::MultiParSel)
461 full_metrics |= multiParSel();
463 bool const single_par = !full_metrics;
464 updateMetrics(single_par);
466 if (flags & Update::FitCursor) {
467 //FIXME: updateMetrics() does not update paragraph position
468 // This is done at draw() time. So we need a redraw!
471 updateMetrics(false);
473 // The screen has already been updated thanks to the
474 // 'buffer_.changed()' call three line above. So no need
479 // tell the frontend to update the screen.
484 void BufferView::updateScrollbar()
486 Text & t = buffer_.text();
487 TextMetrics & tm = text_metrics_[&t];
489 int const parsize = int(t.paragraphs().size() - 1);
490 if (anchor_ref_ > parsize) {
491 anchor_ref_ = parsize;
496 << BOOST_CURRENT_FUNCTION
497 << " Updating scrollbar: height: " << t.paragraphs().size()
498 << " curr par: " << cursor_.bottom().pit()
499 << " default height " << defaultRowHeight() << endl;
501 // It would be better to fix the scrollbar to understand
502 // values in [0..1] and divide everything by wh
504 // estimated average paragraph height:
508 int h = tm.parMetrics(anchor_ref_).height();
510 // Normalize anchor/offset (MV):
511 while (offset_ref_ > h && anchor_ref_ < parsize) {
514 h = tm.parMetrics(anchor_ref_).height();
516 // Look at paragraph heights on-screen
519 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
522 int const h2 = tm.parMetrics(pit).height();
528 int const hav = sumh / nh;
529 // More realistic average paragraph height
534 scrollbarParameters_.height = (parsize + 1) * wh_;
535 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
536 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
540 ScrollbarParameters const & BufferView::scrollbarParameters() const
542 return scrollbarParameters_;
546 void BufferView::scrollDocView(int value)
548 LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
549 << "[ value = " << value << "]" << endl;
551 Text & t = buffer_.text();
552 TextMetrics & tm = text_metrics_[&t];
554 float const bar = value / float(wh_ * t.paragraphs().size());
556 anchor_ref_ = int(bar * t.paragraphs().size());
557 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
558 anchor_ref_ = int(t.paragraphs().size()) - 1;
560 tm.redoParagraph(anchor_ref_);
561 int const h = tm.parMetrics(anchor_ref_).height();
562 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
563 updateMetrics(false);
568 void BufferView::setCursorFromScrollbar()
570 TextMetrics & tm = text_metrics_[&buffer_.text()];
572 int const height = 2 * defaultRowHeight();
573 int const first = height;
574 int const last = height_ - height;
575 Cursor & cur = cursor_;
577 switch (cursorStatus(cur)) {
579 // We reset the cursor because cursorStatus() does not
580 // work when the cursor is within mathed.
581 cur.reset(buffer_.inset());
582 tm.setCursorFromCoordinates(cur, 0, first);
583 cur.clearSelection();
586 // We reset the cursor because cursorStatus() does not
587 // work when the cursor is within mathed.
588 cur.reset(buffer_.inset());
589 tm.setCursorFromCoordinates(cur, 0, last);
590 cur.clearSelection();
593 int const y = getPos(cur, cur.boundary()).y_;
594 int const newy = min(last, max(y, first));
596 cur.reset(buffer_.inset());
597 tm.setCursorFromCoordinates(cur, 0, newy);
603 Change const BufferView::getCurrentChange() const
605 if (!cursor_.selection())
606 return Change(Change::UNCHANGED);
608 DocIterator dit = cursor_.selectionBegin();
609 return dit.paragraph().lookupChange(dit.pos());
613 // this could be used elsewhere as well?
614 // FIXME: This does not work within mathed!
615 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
617 Point const p = getPos(dit, dit.boundary());
620 if (p.y_ > workHeight())
626 void BufferView::saveBookmark(unsigned int idx)
628 // tenatively save bookmark, id and pos will be used to
629 // acturately locate a bookmark in a 'live' lyx session.
630 // pit and pos will be updated with bottom level pit/pos
632 LyX::ref().session().bookmarks().save(
633 FileName(buffer_.fileName()),
634 cursor_.bottom().pit(),
635 cursor_.bottom().pos(),
636 cursor_.paragraph().id(),
641 // emit message signal.
642 message(_("Save bookmark"));
646 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
647 int top_id, pos_type top_pos)
649 bool success = false;
652 cursor_.clearSelection();
654 // if a valid par_id is given, try it first
655 // This is the case for a 'live' bookmark when unique paragraph ID
656 // is used to track bookmarks.
658 ParIterator par = buffer_.getParFromID(top_id);
659 if (par != buffer_.par_iterator_end()) {
660 doc_it = makeDocIterator(par, min(par->size(), top_pos));
661 // Some slices of the iterator may not be
662 // reachable (e.g. closed collapsable inset)
663 // so the dociterator may need to be
664 // shortened. Otherwise, setCursor may crash
665 // lyx when the cursor can not be set to these
667 size_t const n = doc_it.depth();
668 for (size_t i = 0; i < n; ++i)
669 if (doc_it[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
677 // if top_id == 0, or searching through top_id failed
678 // This is the case for a 'restored' bookmark when only bottom
679 // (document level) pit was saved. Because of this, bookmark
680 // restoration is inaccurate. If a bookmark was within an inset,
681 // it will be restored to the left of the outmost inset that contains
683 if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
684 doc_it = doc_iterator_begin(buffer_.inset());
685 doc_it.pit() = bottom_pit;
686 doc_it.pos() = min(bottom_pos, doc_it.paragraph().size());
691 // Note: only bottom (document) level pit is set.
693 // set the current font.
694 cursor_.setCurrentFont();
695 // center the screen on this new position.
703 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
705 if (lyxrc.rtl_support) {
706 if (cursor_.real_current_font.isRightToLeft()) {
707 if (intl_->keymap == Intl::PRIMARY)
710 if (intl_->keymap == Intl::SECONDARY)
715 intl_->getTransManager().translateAndInsert(c, t, cur);
719 int BufferView::workWidth() const
725 void BufferView::updateOffsetRef()
727 // No need to update offset_ref_ in this case.
728 if (!need_centering_)
731 // We are not properly started yet, delay until resizing is
736 CursorSlice & bot = cursor_.bottom();
737 TextMetrics & tm = text_metrics_[bot.text()];
738 ParagraphMetrics const & pm = tm.parMetrics(bot.pit());
739 int y = coordOffset(cursor_, cursor_.boundary()).y_;
740 offset_ref_ = y + pm.ascent() - height_ / 2;
742 need_centering_ = false;
746 void BufferView::center()
748 anchor_ref_ = cursor_.bottom().pit();
749 need_centering_ = true;
753 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
757 Cursor & cur = cursor_;
759 switch (cmd.action) {
762 flag.enabled(!buffer_.undostack().empty());
765 flag.enabled(!buffer_.redostack().empty());
767 case LFUN_FILE_INSERT:
768 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
769 case LFUN_FILE_INSERT_PLAINTEXT:
770 case LFUN_BOOKMARK_SAVE:
771 // FIXME: Actually, these LFUNS should be moved to Text
772 flag.enabled(cur.inTexted());
774 case LFUN_FONT_STATE:
775 case LFUN_LABEL_INSERT:
776 case LFUN_PARAGRAPH_GOTO:
777 // FIXME handle non-trivially
778 case LFUN_OUTLINE_UP:
779 case LFUN_OUTLINE_DOWN:
780 case LFUN_OUTLINE_IN:
781 case LFUN_OUTLINE_OUT:
783 case LFUN_REFERENCE_NEXT:
785 case LFUN_WORD_REPLACE:
788 case LFUN_MARK_TOGGLE:
789 case LFUN_SCREEN_RECENTER:
790 case LFUN_BIBTEX_DATABASE_ADD:
791 case LFUN_BIBTEX_DATABASE_DEL:
792 case LFUN_WORDS_COUNT:
793 case LFUN_NEXT_INSET_TOGGLE:
797 case LFUN_LABEL_GOTO: {
798 flag.enabled(!cmd.argument().empty()
799 || getInsetByCode<InsetRef>(cur, Inset::REF_CODE));
803 case LFUN_CHANGES_TRACK:
805 flag.setOnOff(buffer_.params().trackChanges);
808 case LFUN_CHANGES_OUTPUT:
810 flag.setOnOff(buffer_.params().outputChanges);
813 case LFUN_CHANGES_MERGE:
814 case LFUN_CHANGE_NEXT:
815 case LFUN_ALL_CHANGES_ACCEPT:
816 case LFUN_ALL_CHANGES_REJECT:
817 // TODO: context-sensitive enabling of LFUNs
818 // In principle, these command should only be enabled if there
819 // is a change in the document. However, without proper
820 // optimizations, this will inevitably result in poor performance.
824 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
825 flag.setOnOff(buffer_.params().compressed);
830 case LFUN_SCREEN_DOWN:
834 // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
835 // everywhere else before this can enabled:
836 case LFUN_SCREEN_UP_SELECT:
837 case LFUN_SCREEN_DOWN_SELECT:
849 Update::flags BufferView::dispatch(FuncRequest const & cmd)
851 //lyxerr << BOOST_CURRENT_FUNCTION
852 // << [ cmd = " << cmd << "]" << endl;
854 // Make sure that the cached BufferView is correct.
855 LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
856 << " action[" << cmd.action << ']'
857 << " arg[" << to_utf8(cmd.argument()) << ']'
858 << " x[" << cmd.x << ']'
859 << " y[" << cmd.y << ']'
860 << " button[" << cmd.button() << ']'
863 Cursor & cur = cursor_;
864 // Default Update flags.
865 Update::flags updateFlags = Update::Force | Update::FitCursor;
867 switch (cmd.action) {
870 cur.message(_("Undo"));
871 cur.clearSelection();
872 if (!textUndo(*this)) {
873 cur.message(_("No further undo information"));
874 updateFlags = Update::None;
879 cur.message(_("Redo"));
880 cur.clearSelection();
881 if (!textRedo(*this)) {
882 cur.message(_("No further redo information"));
883 updateFlags = Update::None;
887 case LFUN_FILE_INSERT:
889 menuInsertLyXFile(to_utf8(cmd.argument()));
892 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
894 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
897 case LFUN_FILE_INSERT_PLAINTEXT:
899 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
902 case LFUN_FONT_STATE:
903 cur.message(cur.currentState());
906 case LFUN_BOOKMARK_SAVE:
907 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
910 case LFUN_LABEL_GOTO: {
911 docstring label = cmd.argument();
914 getInsetByCode<InsetRef>(cursor_,
917 label = inset->getParam("reference");
918 // persistent=false: use temp_bookmark
928 case LFUN_PARAGRAPH_GOTO: {
929 int const id = convert<int>(to_utf8(cmd.argument()));
931 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
932 b = theBufferList().next(b)) {
934 ParIterator par = b->getParFromID(id);
935 if (par == b->par_iterator_end()) {
937 << "No matching paragraph found! ["
938 << id << "]." << endl;
941 << "Paragraph " << par->id()
942 << " found in buffer `"
943 << b->fileName() << "'." << endl;
947 setCursor(makeDocIterator(par, 0));
949 // Switch to other buffer view and resend cmd
950 theLyXFunc().dispatch(FuncRequest(
951 LFUN_BUFFER_SWITCH, b->fileName()));
952 theLyXFunc().dispatch(cmd);
953 updateFlags = Update::None;
962 case LFUN_OUTLINE_UP:
963 outline(OutlineUp, cursor_);
964 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
965 updateLabels(buffer_);
967 case LFUN_OUTLINE_DOWN:
968 outline(OutlineDown, cursor_);
969 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
970 updateLabels(buffer_);
972 case LFUN_OUTLINE_IN:
973 outline(OutlineIn, cursor_);
974 updateLabels(buffer_);
976 case LFUN_OUTLINE_OUT:
977 outline(OutlineOut, cursor_);
978 updateLabels(buffer_);
982 gotoInset(this, Inset::NOTE_CODE, false);
985 case LFUN_REFERENCE_NEXT: {
986 vector<Inset_code> tmp;
987 tmp.push_back(Inset::LABEL_CODE);
988 tmp.push_back(Inset::REF_CODE);
989 gotoInset(this, tmp, true);
993 case LFUN_CHANGES_TRACK:
994 buffer_.params().trackChanges = !buffer_.params().trackChanges;
997 case LFUN_CHANGES_OUTPUT:
998 buffer_.params().outputChanges = !buffer_.params().outputChanges;
999 if (buffer_.params().outputChanges) {
1000 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1001 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1002 LaTeXFeatures::isAvailable("xcolor");
1004 if (!dvipost && !xcolorsoul) {
1005 Alert::warning(_("Changes not shown in LaTeX output"),
1006 _("Changes will not be highlighted in LaTeX output, "
1007 "because neither dvipost nor xcolor/soul are installed.\n"
1008 "Please install these packages or redefine "
1009 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1010 } else if (!xcolorsoul) {
1011 Alert::warning(_("Changes not shown in LaTeX output"),
1012 _("Changes will not be highlighted in LaTeX output "
1013 "when using pdflatex, because xcolor and soul are not installed.\n"
1014 "Please install both packages or redefine "
1015 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1020 case LFUN_CHANGE_NEXT:
1021 findNextChange(this);
1024 case LFUN_CHANGES_MERGE:
1025 if (findNextChange(this))
1026 showDialog("changes");
1029 case LFUN_ALL_CHANGES_ACCEPT:
1030 // select complete document
1031 cursor_.reset(buffer_.inset());
1032 cursor_.selHandle(true);
1033 buffer_.text().cursorBottom(cursor_);
1034 // accept everything in a single step to support atomic undo
1035 buffer_.text().acceptOrRejectChanges(cursor_, Text::ACCEPT);
1038 case LFUN_ALL_CHANGES_REJECT:
1039 // select complete document
1040 cursor_.reset(buffer_.inset());
1041 cursor_.selHandle(true);
1042 buffer_.text().cursorBottom(cursor_);
1043 // reject everything in a single step to support atomic undo
1044 // Note: reject does not work recursively; the user may have to repeat the operation
1045 buffer_.text().acceptOrRejectChanges(cursor_, Text::REJECT);
1048 case LFUN_WORD_FIND:
1052 case LFUN_WORD_REPLACE: {
1053 bool has_deleted = false;
1054 if (cur.selection()) {
1055 DocIterator beg = cur.selectionBegin();
1056 DocIterator end = cur.selectionEnd();
1057 if (beg.pit() == end.pit()) {
1058 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1059 if (cur.paragraph().isDeleted(p))
1064 replace(this, cmd, has_deleted);
1069 cur.clearSelection();
1071 cur.message(from_utf8(N_("Mark off")));
1075 cur.clearSelection();
1078 cur.message(from_utf8(N_("Mark on")));
1081 case LFUN_MARK_TOGGLE:
1082 cur.clearSelection();
1085 cur.message(from_utf8(N_("Mark removed")));
1088 cur.message(from_utf8(N_("Mark set")));
1093 case LFUN_SCREEN_RECENTER:
1097 case LFUN_BIBTEX_DATABASE_ADD: {
1098 Cursor tmpcur = cursor_;
1099 findInset(tmpcur, Inset::BIBTEX_CODE, false);
1100 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1101 Inset::BIBTEX_CODE);
1103 if (inset->addDatabase(to_utf8(cmd.argument())))
1104 buffer_.updateBibfilesCache();
1109 case LFUN_BIBTEX_DATABASE_DEL: {
1110 Cursor tmpcur = cursor_;
1111 findInset(tmpcur, Inset::BIBTEX_CODE, false);
1112 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1113 Inset::BIBTEX_CODE);
1115 if (inset->delDatabase(to_utf8(cmd.argument())))
1116 buffer_.updateBibfilesCache();
1121 case LFUN_WORDS_COUNT: {
1122 DocIterator from, to;
1123 if (cur.selection()) {
1124 from = cur.selectionBegin();
1125 to = cur.selectionEnd();
1127 from = doc_iterator_begin(buffer_.inset());
1128 to = doc_iterator_end(buffer_.inset());
1130 int const count = countWords(from, to);
1133 if (cur.selection())
1134 message = bformat(_("%1$d words in selection."),
1137 message = bformat(_("%1$d words in document."),
1141 if (cur.selection())
1142 message = _("One word in selection.");
1144 message = _("One word in document.");
1147 Alert::information(_("Count words"), message);
1151 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1152 // turn compression on/off
1153 buffer_.params().compressed = !buffer_.params().compressed;
1156 case LFUN_NEXT_INSET_TOGGLE: {
1157 // this is the real function we want to invoke
1158 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1159 // if there is an inset at cursor, see whether it
1161 Inset * inset = cur.nextInset();
1163 if (inset->isActive()) {
1164 Cursor tmpcur = cur;
1165 tmpcur.pushLeft(*inset);
1166 inset->dispatch(tmpcur, tmpcmd);
1167 if (tmpcur.result().dispatched()) {
1170 } else if (inset->editable() == Inset::IS_EDITABLE) {
1171 inset->edit(cur, true);
1174 // if it did not work, try the underlying inset.
1175 if (!cur.result().dispatched())
1176 cur.dispatch(tmpcmd);
1178 if (cur.result().dispatched())
1179 cur.clearSelection();
1184 case LFUN_SCREEN_UP:
1185 case LFUN_SCREEN_DOWN: {
1186 Point p = getPos(cur, cur.boundary());
1187 if (p.y_ < 0 || p.y_ > height_) {
1188 // The cursor is off-screen so recenter before proceeding.
1190 updateMetrics(false);
1191 //FIXME: updateMetrics() does not update paragraph position
1192 // This is done at draw() time. So we need a redraw!
1194 p = getPos(cur, cur.boundary());
1196 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1197 cur.reset(buffer_.inset());
1198 text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1199 //FIXME: what to do with cur.x_target()?
1201 // The metrics are already up to date. see scroll()
1202 updateFlags = Update::None;
1206 case LFUN_SCREEN_UP_SELECT:
1207 case LFUN_SCREEN_DOWN_SELECT: {
1208 cur.selHandle(true);
1209 size_t initial_depth = cur.depth();
1210 Point const p = getPos(cur, cur.boundary());
1211 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1212 // FIXME: We need to verify if the cursor stayed within an inset...
1213 //cur.reset(buffer_.inset());
1214 text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1216 while (cur.depth() > initial_depth) {
1219 // FIXME: we need to do a redraw again because of the selection
1221 updateFlags = Update::Force | Update::FitCursor;
1226 updateFlags = Update::None;
1233 docstring const BufferView::requestSelection()
1235 Cursor & cur = cursor_;
1237 if (!cur.selection()) {
1238 xsel_cache_.set = false;
1242 if (!xsel_cache_.set ||
1243 cur.top() != xsel_cache_.cursor ||
1244 cur.anchor_.top() != xsel_cache_.anchor)
1246 xsel_cache_.cursor = cur.top();
1247 xsel_cache_.anchor = cur.anchor_.top();
1248 xsel_cache_.set = cur.selection();
1249 return cur.selectionAsString(false);
1255 void BufferView::clearSelection()
1257 cursor_.clearSelection();
1258 // Clear the selection buffer. Otherwise a subsequent
1259 // middle-mouse-button paste would use the selection buffer,
1260 // not the more current external selection.
1261 cap::clearSelection();
1262 xsel_cache_.set = false;
1263 // The buffer did not really change, but this causes the
1264 // redraw we need because we cleared the selection above.
1269 void BufferView::resize(int width, int height)
1271 // Update from work area
1275 updateMetrics(false);
1279 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1281 TextMetrics & tm = text_metrics_[&text];
1282 Inset * inset = tm.checkInsetHit(x, y);
1286 if (!inset->descendable())
1287 // No need to go further down if the inset is not
1291 size_t cell_number = inset->nargs();
1292 // Check all the inner cell.
1293 for (size_t i = 0; i != cell_number; ++i) {
1294 Text const * inner_text = inset->getText(i);
1297 Inset const * inset_deeper =
1298 getCoveringInset(*inner_text, x, y);
1300 return inset_deeper;
1308 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1310 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1312 // This is only called for mouse related events including
1313 // LFUN_FILE_OPEN generated by drag-and-drop.
1314 FuncRequest cmd = cmd0;
1317 cur.push(buffer_.inset());
1318 cur.selection() = cursor_.selection();
1320 // Either the inset under the cursor or the
1321 // surrounding Text will handle this event.
1323 // make sure we stay within the screen...
1324 cmd.y = min(max(cmd.y, -1), height_);
1326 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1328 // Get inset under mouse, if there is one.
1329 Inset const * covering_inset =
1330 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1331 if (covering_inset == last_inset_)
1332 // Same inset, no need to do anything...
1335 bool need_redraw = false;
1336 // const_cast because of setMouseHover().
1337 Inset * inset = const_cast<Inset *>(covering_inset);
1339 // Remove the hint on the last hovered inset (if any).
1340 need_redraw |= last_inset_->setMouseHover(false);
1342 // Highlighted the newly hovered inset (if any).
1343 need_redraw |= inset->setMouseHover(true);
1344 last_inset_ = inset;
1348 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1349 // not expose the button for redraw. We adjust here the metrics dimension
1350 // to enable a full redraw in any case as this is not costly.
1351 TextMetrics & tm = text_metrics_[&buffer_.text()];
1352 std::pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
1353 std::pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1354 int y1 = firstpm.second->position() - firstpm.second->ascent();
1355 int y2 = lastpm.second->position() + lastpm.second->descent();
1356 metrics_info_ = ViewMetricsInfo(firstpm.first, lastpm.first, y1, y2,
1357 FullScreenUpdate, buffer_.text().paragraphs().size());
1358 // Reinitialize anchor to first pit.
1359 anchor_ref_ = firstpm.first;
1361 LYXERR(Debug::PAINTING)
1362 << "Mouse hover detected at: (" << cmd.x << ", " << cmd.y << ")"
1363 << "\nTriggering redraw: y1: " << y1 << " y2: " << y2
1364 << " pit1: " << firstpm.first << " pit2: " << lastpm.first << endl;
1366 // This event (moving without mouse click) is not passed further.
1367 // This should be changed if it is further utilized.
1371 // Build temporary cursor.
1372 Inset * inset = text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1374 // Put anchor at the same position.
1377 // Try to dispatch to an non-editable inset near this position
1378 // via the temp cursor. If the inset wishes to change the real
1379 // cursor it has to do so explicitly by using
1380 // cur.bv().cursor() = cur; (or similar)
1382 inset->dispatch(cur, cmd);
1385 // Now dispatch to the temporary cursor. If the real cursor should
1386 // be modified, the inset's dispatch has to do so explicitly.
1387 if (!cur.result().dispatched())
1390 //Do we have a selection?
1391 theSelection().haveSelection(cursor().selection());
1393 // Redraw if requested and necessary.
1394 if (cur.result().dispatched() && cur.result().update())
1395 return update(cur.result().update());
1401 void BufferView::scroll(int y)
1410 void BufferView::scrollDown(int offset)
1412 Text * text = &buffer_.text();
1413 TextMetrics & tm = text_metrics_[text];
1414 int ymax = height_ + offset;
1416 std::pair<pit_type, ParagraphMetrics const *> last = tm.last();
1417 int bottom_pos = last.second->position() + last.second->descent();
1418 if (last.first + 1 == int(text->paragraphs().size())) {
1419 if (bottom_pos <= height_)
1421 offset = min(offset, bottom_pos - height_);
1424 if (bottom_pos > ymax)
1426 tm.newParMetricsDown();
1428 offset_ref_ += offset;
1429 updateMetrics(false);
1434 void BufferView::scrollUp(int offset)
1436 Text * text = &buffer_.text();
1437 TextMetrics & tm = text_metrics_[text];
1438 int ymin = - offset;
1440 std::pair<pit_type, ParagraphMetrics const *> first = tm.first();
1441 int top_pos = first.second->position() - first.second->ascent();
1442 if (first.first == 0) {
1445 offset = min(offset, - top_pos);
1450 tm.newParMetricsUp();
1452 offset_ref_ -= offset;
1453 updateMetrics(false);
1458 void BufferView::setCursorFromRow(int row)
1463 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1465 cursor_.reset(buffer_.inset());
1467 buffer_.text().setCursor(cursor_, 0, 0);
1469 buffer_.text().setCursor(cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1473 void BufferView::gotoLabel(docstring const & label)
1475 for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1476 vector<docstring> labels;
1477 it->getLabelList(buffer_, labels);
1478 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1487 TextMetrics const & BufferView::textMetrics(Text const * t) const
1489 return const_cast<BufferView *>(this)->textMetrics(t);
1493 TextMetrics & BufferView::textMetrics(Text const * t)
1495 TextMetricsCache::iterator tmc_it = text_metrics_.find(t);
1496 if (tmc_it == text_metrics_.end()) {
1497 tmc_it = text_metrics_.insert(
1498 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1500 return tmc_it->second;
1504 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1507 return textMetrics(t).parMetrics(pit);
1511 int BufferView::workHeight() const
1517 void BufferView::setCursor(DocIterator const & dit)
1519 size_t const n = dit.depth();
1520 for (size_t i = 0; i < n; ++i)
1521 dit[i].inset().edit(cursor_, true);
1523 cursor_.setCursor(dit);
1524 cursor_.selection() = false;
1528 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1530 // Would be wrong to delete anything if we have a selection.
1531 if (cur.selection())
1534 bool need_anchor_change = false;
1535 bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1536 need_anchor_change);
1538 if (need_anchor_change)
1544 updateLabels(buffer_);
1546 updateMetrics(false);
1552 bool BufferView::mouseSetCursor(Cursor & cur)
1554 BOOST_ASSERT(&cur.bv() == this);
1556 // this event will clear selection so we save selection for
1557 // persistent selection
1558 cap::saveSelection(cursor());
1560 // Has the cursor just left the inset?
1561 bool badcursor = false;
1562 bool leftinset = (&cursor_.inset() != &cur.inset());
1564 badcursor = notifyCursorLeaves(cursor_, cur);
1566 // do the dEPM magic if needed
1567 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1568 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1569 // the leftinset bool would not be necessary (badcursor instead).
1570 bool update = leftinset;
1571 if (!badcursor && cursor_.inTexted())
1572 update |= checkDepm(cur, cursor_);
1574 // if the cursor was in an empty script inset and the new
1575 // position is in the nucleus of the inset, notifyCursorLeaves
1576 // will kill the script inset itself. So we check all the
1577 // elements of the cursor to make sure that they are correct.
1578 // For an example, see bug 2933:
1579 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1580 // The code below could maybe be moved to a DocIterator method.
1581 //lyxerr << "cur before " << cur <<std::endl;
1582 DocIterator dit(cur.inset());
1583 dit.push_back(cur.bottom());
1585 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1586 dit.push_back(cur[i]);
1589 //lyxerr << "5 cur after" << dit <<std::endl;
1591 cursor_.setCursor(dit);
1592 cursor_.boundary(cur.boundary());
1593 cursor_.clearSelection();
1599 void BufferView::putSelectionAt(DocIterator const & cur,
1600 int length, bool backwards)
1602 cursor_.clearSelection();
1608 cursor_.pos() += length;
1609 cursor_.setSelection(cursor_, -length);
1611 cursor_.setSelection(cursor_, length);
1616 Cursor & BufferView::cursor()
1622 Cursor const & BufferView::cursor() const
1628 pit_type BufferView::anchor_ref() const
1634 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1636 return metrics_info_;
1640 bool BufferView::singleParUpdate()
1642 Text & buftext = buffer_.text();
1643 pit_type const bottom_pit = cursor_.bottom().pit();
1644 TextMetrics & tm = textMetrics(&buftext);
1645 int old_height = tm.parMetrics(bottom_pit).height();
1647 // In Single Paragraph mode, rebreak only
1648 // the (main text, not inset!) paragraph containing the cursor.
1649 // (if this paragraph contains insets etc., rebreaking will
1650 // recursively descend)
1651 tm.redoParagraph(bottom_pit);
1652 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
1653 if (pm.height() != old_height)
1654 // Paragraph height has changed so we cannot proceed to
1655 // the singlePar optimisation.
1658 int y1 = pm.position() - pm.ascent();
1659 int y2 = pm.position() + pm.descent();
1660 metrics_info_ = ViewMetricsInfo(bottom_pit, bottom_pit, y1, y2,
1661 SingleParUpdate, buftext.paragraphs().size());
1662 LYXERR(Debug::PAINTING)
1663 << BOOST_CURRENT_FUNCTION
1666 << " pit: " << bottom_pit
1673 void BufferView::updateMetrics(bool singlepar)
1675 if (singlepar && singleParUpdate())
1676 // No need to update the full screen metrics.
1679 Text & buftext = buffer_.text();
1680 pit_type const npit = int(buftext.paragraphs().size());
1682 if (anchor_ref_ > int(npit - 1)) {
1683 anchor_ref_ = int(npit - 1);
1687 // Clear out the position cache in case of full screen redraw,
1688 coord_cache_.clear();
1690 // Clear out paragraph metrics to avoid having invalid metrics
1691 // in the cache from paragraphs not relayouted below
1692 // The complete text metrics will be redone.
1693 text_metrics_.clear();
1695 TextMetrics & tm = textMetrics(&buftext);
1697 pit_type const pit = anchor_ref_;
1701 // Rebreak anchor paragraph.
1702 tm.redoParagraph(pit);
1704 // Take care of anchor offset if case a recentering is needed.
1707 int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1709 // Redo paragraphs above anchor if necessary.
1711 while (y1 > 0 && pit1 > 0) {
1712 y1 -= tm.parMetrics(pit1).ascent();
1714 tm.redoParagraph(pit1);
1715 y1 -= tm.parMetrics(pit1).descent();
1718 // Take care of ascent of first line
1719 y1 -= tm.parMetrics(pit1).ascent();
1721 // Normalize anchor for next time
1725 // Grey at the beginning is ugly
1726 if (pit1 == 0 && y1 > 0) {
1732 // Redo paragraphs below the anchor if necessary.
1734 while (y2 < height_ && pit2 < int(npit) - 1) {
1735 y2 += tm.parMetrics(pit2).descent();
1737 tm.redoParagraph(pit2);
1738 y2 += tm.parMetrics(pit2).ascent();
1741 // Take care of descent of last line
1742 y2 += tm.parMetrics(pit2).descent();
1744 LYXERR(Debug::PAINTING)
1745 << BOOST_CURRENT_FUNCTION
1748 << " pit1: " << pit1
1749 << " pit2: " << pit2
1750 << " npit: " << npit
1754 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1755 FullScreenUpdate, npit);
1757 if (lyxerr.debugging(Debug::WORKAREA)) {
1758 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1759 coord_cache_.dump();
1764 void BufferView::menuInsertLyXFile(string const & filenm)
1766 BOOST_ASSERT(cursor_.inTexted());
1767 string filename = filenm;
1769 if (filename.empty()) {
1770 // Launch a file browser
1772 string initpath = lyxrc.document_path;
1773 string const trypath = buffer_.filePath();
1774 // If directory is writeable, use this as default.
1775 if (isDirWriteable(FileName(trypath)))
1779 FileDialog fileDlg(_("Select LyX document to insert"),
1781 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1782 make_pair(_("Examples|#E#e"),
1783 from_utf8(addPath(package().system_support().absFilename(),
1786 FileDialog::Result result =
1787 fileDlg.open(from_utf8(initpath),
1788 FileFilterList(_("LyX Documents (*.lyx)")),
1791 if (result.first == FileDialog::Later)
1795 filename = to_utf8(result.second);
1797 // check selected filename
1798 if (filename.empty()) {
1799 // emit message signal.
1800 message(_("Canceled."));
1805 // Get absolute path of file and add ".lyx"
1806 // to the filename if necessary
1807 filename = fileSearch(string(), filename, "lyx").absFilename();
1809 docstring const disp_fn = makeDisplayPath(filename);
1810 // emit message signal.
1811 message(bformat(_("Inserting document %1$s..."), disp_fn));
1814 Buffer buf("", false);
1815 if (lyx::loadLyXFile(&buf, FileName(filename))) {
1816 ErrorList & el = buffer_.errorList("Parse");
1817 // Copy the inserted document error list into the current buffer one.
1818 el = buf.errorList("Parse");
1819 recordUndo(cursor_);
1820 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1821 buf.params().getTextClassPtr(), el);
1822 res = _("Document %1$s inserted.");
1824 res = _("Could not insert document %1$s");
1826 // emit message signal.
1827 message(bformat(res, disp_fn));
1828 buffer_.errors("Parse");
1829 updateMetrics(false);
1833 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1839 // Addup contribution of nested insets, from inside to outside,
1840 // keeping the outer paragraph for a special handling below
1841 for (size_t i = dit.depth() - 1; i >= 1; --i) {
1842 CursorSlice const & sl = dit[i];
1846 // get relative position inside sl.inset()
1847 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
1849 // Make relative position inside of the edited inset relative to sl.inset()
1853 // In case of an RTL inset, the edited inset will be positioned to the left
1856 bool boundary_i = boundary && i + 1 == dit.depth();
1857 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
1862 // remember width for the case that sl.inset() is positioned in an RTL inset
1863 if (i && dit[i - 1].text()) {
1864 // If this Inset is inside a Text Inset, retrieve the Dimension
1865 // from the containing text instead of using Inset::dimension() which
1866 // might not be implemented.
1867 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
1868 // elimination of Inset::dim_ cache. This coordOffset() method needs
1869 // to be rewritten in light of the new design.
1870 Dimension const & dim = parMetrics(dit[i - 1].text(),
1871 dit[i - 1].pit()).insetDimension(&sl.inset());
1874 Dimension const dim = sl.inset().dimension(*this);
1878 //lyxerr << "Cursor::getPos, i: "
1879 // << i << " x: " << xx << " y: " << y << endl;
1882 // Add contribution of initial rows of outermost paragraph
1883 CursorSlice const & sl = dit[0];
1884 TextMetrics const & tm = textMetrics(sl.text());
1885 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
1886 BOOST_ASSERT(!pm.rows().empty());
1887 y -= pm.rows()[0].ascent();
1889 // FIXME: document this mess
1891 if (sl.pos() > 0 && dit.depth() == 1) {
1893 if (pos && boundary)
1895 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << std::endl;
1896 rend = pm.pos2row(pos);
1898 rend = pm.pos2row(sl.pos());
1900 size_t rend = pm.pos2row(sl.pos());
1902 for (size_t rit = 0; rit != rend; ++rit)
1903 y += pm.rows()[rit].height();
1904 y += pm.rows()[rend].ascent();
1906 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
1908 // Make relative position from the nested inset now bufferview absolute.
1909 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
1912 // In the RTL case place the nested inset at the left of the cursor in
1913 // the outer paragraph
1914 bool boundary_1 = boundary && 1 == dit.depth();
1915 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
1923 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
1925 CursorSlice const & bot = dit.bottom();
1926 TextMetrics const & tm = textMetrics(bot.text());
1927 if (!tm.has(bot.pit()))
1928 return Point(-1, -1);
1930 Point p = coordOffset(dit, boundary); // offset from outer paragraph
1931 p.y_ += tm.parMetrics(bot.pit()).position();
1936 void BufferView::draw(frontend::Painter & pain)
1938 PainterInfo pi(this, pain);
1939 // Should the whole screen, including insets, be refreshed?
1940 // FIXME: We should also distinguish DecorationUpdate to avoid text
1941 // drawing if possible. This is not possible to do easily right now
1942 // because of the single backing pixmap.
1943 pi.full_repaint = metrics_info_.update_strategy != SingleParUpdate;
1945 if (pi.full_repaint)
1946 // Clear background (if not delegated to rows)
1947 pain.fillRectangle(0, metrics_info_.y1, width_,
1948 metrics_info_.y2 - metrics_info_.y1,
1949 buffer_.inset().backgroundColor());
1951 LYXERR(Debug::PAINTING) << "\t\t*** START DRAWING ***" << endl;
1952 Text & text = buffer_.text();
1953 TextMetrics const & tm = text_metrics_[&text];
1954 int y = metrics_info_.y1 + tm.parMetrics(metrics_info_.p1).ascent();
1955 if (!pi.full_repaint)
1956 tm.drawParagraph(pi, metrics_info_.p1, 0, y);
1959 LYXERR(Debug::PAINTING) << "\n\t\t*** END DRAWING ***" << endl;
1961 // and grey out above (should not happen later)
1962 // lyxerr << "par ascent: " << text.getPar(metrics_info_.p1).ascent() << endl;
1963 if (metrics_info_.y1 > 0
1964 && metrics_info_.update_strategy == FullScreenUpdate)
1965 pain.fillRectangle(0, 0, width_, metrics_info_.y1, Color::bottomarea);
1967 // and possibly grey out below
1968 // lyxerr << "par descent: " << text.getPar(metrics_info_.p1).ascent() << endl;
1969 if (metrics_info_.y2 < height_
1970 && metrics_info_.update_strategy == FullScreenUpdate)
1971 pain.fillRectangle(0, metrics_info_.y2, width_,
1972 height_ - metrics_info_.y2, Color::bottomarea);