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 "CoordCache.h"
25 #include "CutAndPaste.h"
26 #include "DispatchResult.h"
27 #include "EmbeddedFiles.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"
42 #include "MetricsInfo.h"
43 #include "Paragraph.h"
44 #include "paragraph_funcs.h"
45 #include "ParagraphParameters.h"
46 #include "ParIterator.h"
49 #include "TextClass.h"
50 #include "TextMetrics.h"
53 #include "WordLangTuple.h"
55 #include "insets/InsetBibtex.h"
56 #include "insets/InsetCommand.h" // ChangeRefs
57 #include "insets/InsetRef.h"
58 #include "insets/InsetText.h"
60 #include "frontends/alert.h"
61 #include "frontends/Application.h"
62 #include "frontends/Delegates.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/debug.h"
71 #include "support/ExceptionMessage.h"
72 #include "support/filetools.h"
73 #include "support/gettext.h"
74 #include "support/lstrings.h"
75 #include "support/Package.h"
76 #include "support/types.h"
85 using namespace lyx::support;
89 namespace Alert = frontend::Alert;
93 /// Return an inset of this class if it exists at the current cursor position
95 T * getInsetByCode(Cursor const & cur, InsetCode code)
98 Inset * inset = it.nextInset();
99 if (inset && inset->lyxCode() == code)
100 return static_cast<T*>(inset);
105 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
108 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
109 docstring const & contents)
111 DocIterator tmpdit = dit;
114 Inset const * inset = tmpdit.nextInset();
116 && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
117 && (contents.empty() ||
118 static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
122 tmpdit.forwardInset();
129 /// Looks for next inset with one of the given codes.
130 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
134 DocIterator tmpdit = dit;
135 tmpdit.forwardInset();
140 Inset const * inset = tmpdit.nextInset();
142 && std::find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
143 contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
147 if (!findNextInset(tmpdit, codes, contents)) {
148 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
149 tmpdit = doc_iterator_begin(tmpdit.bottom().inset());
150 if (!findNextInset(tmpdit, codes, contents))
161 /// Looks for next inset with the given code
162 void findInset(DocIterator & dit, InsetCode code, bool same_content)
164 findInset(dit, vector<InsetCode>(1, code), same_content);
168 /// Moves cursor to the next inset with one of the given codes.
169 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
172 Cursor tmpcur = bv->cursor();
173 if (!findInset(tmpcur, codes, same_content)) {
174 bv->cursor().message(_("No more insets"));
178 tmpcur.clearSelection();
179 bv->setCursor(tmpcur);
184 /// Moves cursor to the next inset with given code.
185 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
187 gotoInset(bv, vector<InsetCode>(1, code), same_content);
191 /// A map from a Text to the associated text metrics
192 typedef map<Text const *, TextMetrics> TextMetricsCache;
194 enum ScreenUpdateStrategy {
204 /////////////////////////////////////////////////////////////////////
208 /////////////////////////////////////////////////////////////////////
210 struct BufferView::Private
212 Private(BufferView & bv): wh_(0), cursor_(bv),
213 anchor_pit_(0), anchor_ypos_(0),
214 last_inset_(0), gui_(0)
218 ScrollbarParameters scrollbarParameters_;
220 ScreenUpdateStrategy update_strategy_;
222 CoordCache coord_cache_;
224 /// Estimated average par height for scrollbar.
226 /// this is used to handle XSelection events in the right manner.
235 pit_type anchor_pit_;
239 vector<int> par_height_;
241 /// keyboard mapping object.
244 /// last visited inset.
245 /** kept to send setMouseHover(false).
246 * Not owned, so don't delete.
250 mutable TextMetricsCache text_metrics_;
253 /** Not owned, so don't delete.
255 frontend::GuiBufferViewDelegate * gui_;
259 BufferView::BufferView(Buffer & buf)
260 : width_(0), height_(0), buffer_(buf), d(new Private(*this))
262 d->xsel_cache_.set = false;
263 d->intl_.initKeyMapper(lyxrc.use_kbmap);
265 d->cursor_.push(buffer_.inset());
266 d->cursor_.resetAnchor();
267 d->cursor_.setCurrentFont();
269 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
270 graphics::Previews::get().generateBufferPreviews(buffer_);
274 BufferView::~BufferView()
276 // current buffer is going to be switched-off, save cursor pos
277 // Ideally, the whole cursor stack should be saved, but session
278 // currently can only handle bottom (whole document) level pit and pos.
279 // That is to say, if a cursor is in a nested inset, it will be
280 // restore to the left of the top level inset.
281 LastFilePosSection::FilePos fp;
282 fp.pit = d->cursor_.bottom().pit();
283 fp.pos = d->cursor_.bottom().pos();
284 LyX::ref().session().lastFilePos().save(buffer_.fileName(), fp);
290 Intl & BufferView::getIntl()
296 Intl const & BufferView::getIntl() const
302 CoordCache & BufferView::coordCache()
304 return d->coord_cache_;
308 CoordCache const & BufferView::coordCache() const
310 return d->coord_cache_;
314 Buffer & BufferView::buffer()
320 Buffer const & BufferView::buffer() const
326 bool BufferView::fitCursor()
328 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
329 frontend::FontMetrics const & fm =
330 theFontMetrics(d->cursor_.getFont().fontInfo());
331 int const asc = fm.maxAscent();
332 int const des = fm.maxDescent();
333 Point const p = getPos(d->cursor_, d->cursor_.boundary());
334 if (p.y_ - asc >= 0 && p.y_ + des < height_)
341 void BufferView::processUpdateFlags(Update::flags flags)
343 // last_inset_ points to the last visited inset. This pointer may become
344 // invalid because of keyboard editing. Since all such operations
345 // causes screen update(), I reset last_inset_ to avoid such a problem.
347 // This is close to a hot-path.
348 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
349 << "[fitcursor = " << (flags & Update::FitCursor)
350 << ", forceupdate = " << (flags & Update::Force)
351 << ", singlepar = " << (flags & Update::SinglePar)
352 << "] buffer: " << &buffer_);
354 buffer_.updateMacros();
356 // Now do the first drawing step if needed. This consists on updating
357 // the CoordCache in updateMetrics().
358 // The second drawing step is done in WorkArea::redraw() if needed.
360 // Case when no explicit update is requested.
362 // no need to redraw anything.
363 d->update_strategy_ = NoScreenUpdate;
367 if (flags == Update::Decoration) {
368 d->update_strategy_ = DecorationUpdate;
373 if (flags == Update::FitCursor
374 || flags == (Update::Decoration | Update::FitCursor)) {
375 // tell the frontend to update the screen if needed.
380 if (flags & Update::Decoration) {
381 d->update_strategy_ = DecorationUpdate;
385 // no screen update is needed.
386 d->update_strategy_ = NoScreenUpdate;
390 bool const full_metrics = flags & Update::Force || !singleParUpdate();
393 // We have to update the full screen metrics.
396 if (!(flags & Update::FitCursor)) {
397 // Nothing to do anymore. Trigger a redraw and return
402 // updateMetrics() does not update paragraph position
403 // This is done at draw() time. So we need a redraw!
407 // The cursor is off screen so ensure it is visible.
414 void BufferView::updateScrollbar()
419 // We prefer fixed size line scrolling.
420 d->scrollbarParameters_.single_step = defaultRowHeight();
421 // We prefer full screen page scrolling.
422 d->scrollbarParameters_.page_step = height_;
424 Text & t = buffer_.text();
425 TextMetrics & tm = d->text_metrics_[&t];
427 LYXERR(Debug::GUI, " Updating scrollbar: height: "
428 << t.paragraphs().size()
429 << " curr par: " << d->cursor_.bottom().pit()
430 << " default height " << defaultRowHeight());
432 int const parsize = int(t.paragraphs().size());
433 if (d->par_height_.size() != parsize) {
434 d->par_height_.clear();
435 // FIXME: We assume a default paragraph height of 2 rows. This
436 // should probably be pondered with the screen width.
437 d->par_height_.resize(parsize, defaultRowHeight() * 2);
440 // Look at paragraph heights on-screen
441 pair<pit_type, ParagraphMetrics const *> first = tm.first();
442 pair<pit_type, ParagraphMetrics const *> last = tm.last();
443 for (pit_type pit = first.first; pit <= last.first; ++pit) {
444 d->par_height_[pit] = tm.parMetrics(pit).height();
445 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
446 << d->par_height_[pit]);
449 int top_pos = first.second->position() - first.second->ascent();
450 int bottom_pos = last.second->position() + last.second->descent();
451 bool first_visible = first.first == 0 && top_pos >= 0;
452 bool last_visible = last.first == parsize - 1 && bottom_pos <= height_;
453 if (first_visible && last_visible) {
454 d->scrollbarParameters_.min = 0;
455 d->scrollbarParameters_.max = 0;
459 d->scrollbarParameters_.min = top_pos;
460 for (size_t i = 0; i != first.first; ++i)
461 d->scrollbarParameters_.min -= d->par_height_[i];
462 d->scrollbarParameters_.max = bottom_pos;
463 for (size_t i = last.first + 1; i != parsize; ++i)
464 d->scrollbarParameters_.max += d->par_height_[i];
466 d->scrollbarParameters_.position = 0;
467 // The reference is the top position so we remove one page.
468 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
472 ScrollbarParameters const & BufferView::scrollbarParameters() const
474 return d->scrollbarParameters_;
478 docstring BufferView::toolTip(int x, int y) const
480 // Get inset under mouse, if there is one.
481 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
483 // No inset, no tooltip...
485 return covering_inset->toolTip(*this, x, y);
489 docstring BufferView::contextMenu(int x, int y) const
491 // Get inset under mouse, if there is one.
492 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
494 return covering_inset->contextMenu(*this, x, y);
496 // FIXME: Do something more elaborate here.
497 return from_ascii("edit");
501 void BufferView::scrollDocView(int value)
503 int const offset = value - d->scrollbarParameters_.position;
504 // If the offset is less than 2 screen height, prefer to scroll instead.
505 if (abs(offset) <= 2 * height_) {
510 // cut off at the top
511 if (value <= d->scrollbarParameters_.min) {
512 DocIterator dit = doc_iterator_begin(buffer_.inset());
514 LYXERR(Debug::SCROLLING, "scroll to top");
518 // cut off at the bottom
519 if (value >= d->scrollbarParameters_.max) {
520 DocIterator dit = doc_iterator_end(buffer_.inset());
523 LYXERR(Debug::SCROLLING, "scroll to bottom");
527 // find paragraph at target position
528 int par_pos = d->scrollbarParameters_.min;
530 for (; i != d->par_height_.size(); ++i) {
531 par_pos += d->par_height_[i];
532 if (par_pos >= value)
536 if (par_pos < value) {
537 // It seems we didn't find the correct pit so stay on the safe side and
539 LYXERR0("scrolling position not found!");
540 scrollDocView(d->scrollbarParameters_.max);
544 DocIterator dit = doc_iterator_begin(buffer_.inset());
546 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
551 // FIXME: this method is not working well.
552 void BufferView::setCursorFromScrollbar()
554 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
556 int const height = 2 * defaultRowHeight();
557 int const first = height;
558 int const last = height_ - height;
559 Cursor & cur = d->cursor_;
561 switch (cursorStatus(cur)) {
563 // We reset the cursor because cursorStatus() does not
564 // work when the cursor is within mathed.
565 cur.reset(buffer_.inset());
566 tm.setCursorFromCoordinates(cur, 0, first);
567 cur.clearSelection();
570 // We reset the cursor because cursorStatus() does not
571 // work when the cursor is within mathed.
572 cur.reset(buffer_.inset());
573 tm.setCursorFromCoordinates(cur, 0, last);
574 cur.clearSelection();
577 int const y = getPos(cur, cur.boundary()).y_;
578 int const newy = min(last, max(y, first));
580 cur.reset(buffer_.inset());
581 tm.setCursorFromCoordinates(cur, 0, newy);
587 Change const BufferView::getCurrentChange() const
589 if (!d->cursor_.selection())
590 return Change(Change::UNCHANGED);
592 DocIterator dit = d->cursor_.selectionBegin();
593 return dit.paragraph().lookupChange(dit.pos());
597 // this could be used elsewhere as well?
598 // FIXME: This does not work within mathed!
599 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
601 Point const p = getPos(dit, dit.boundary());
604 if (p.y_ > workHeight())
610 void BufferView::saveBookmark(unsigned int idx)
612 // tenatively save bookmark, id and pos will be used to
613 // acturately locate a bookmark in a 'live' lyx session.
614 // pit and pos will be updated with bottom level pit/pos
616 LyX::ref().session().bookmarks().save(
618 d->cursor_.bottom().pit(),
619 d->cursor_.bottom().pos(),
620 d->cursor_.paragraph().id(),
625 // emit message signal.
626 message(_("Save bookmark"));
630 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
631 int top_id, pos_type top_pos)
633 bool success = false;
636 d->cursor_.clearSelection();
638 // if a valid par_id is given, try it first
639 // This is the case for a 'live' bookmark when unique paragraph ID
640 // is used to track bookmarks.
642 ParIterator par = buffer_.getParFromID(top_id);
643 if (par != buffer_.par_iterator_end()) {
644 doc_it = makeDocIterator(par, min(par->size(), top_pos));
645 // Some slices of the iterator may not be
646 // reachable (e.g. closed collapsable inset)
647 // so the dociterator may need to be
648 // shortened. Otherwise, setCursor may crash
649 // lyx when the cursor can not be set to these
651 size_t const n = doc_it.depth();
652 for (size_t i = 0; i < n; ++i)
653 if (doc_it[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
661 // if top_id == 0, or searching through top_id failed
662 // This is the case for a 'restored' bookmark when only bottom
663 // (document level) pit was saved. Because of this, bookmark
664 // restoration is inaccurate. If a bookmark was within an inset,
665 // it will be restored to the left of the outmost inset that contains
667 if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
668 doc_it = doc_iterator_begin(buffer_.inset());
669 doc_it.pit() = bottom_pit;
670 doc_it.pos() = min(bottom_pos, doc_it.paragraph().size());
675 // Note: only bottom (document) level pit is set.
677 // set the current font.
678 d->cursor_.setCurrentFont();
679 // To center the screen on this new position we need the
680 // paragraph position which is computed at draw() time.
681 // So we need a redraw!
691 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
693 if (lyxrc.rtl_support) {
694 if (d->cursor_.real_current_font.isRightToLeft()) {
695 if (d->intl_.keymap == Intl::PRIMARY)
696 d->intl_.keyMapSec();
698 if (d->intl_.keymap == Intl::SECONDARY)
699 d->intl_.keyMapPrim();
703 d->intl_.getTransManager().translateAndInsert(c, t, cur);
707 int BufferView::workWidth() const
713 void BufferView::showCursor()
715 showCursor(d->cursor_);
719 void BufferView::showCursor(DocIterator const & dit)
721 // We are not properly started yet, delay until resizing is
726 LYXERR(Debug::SCROLLING, "recentering!");
728 CursorSlice const & bot = dit.bottom();
729 TextMetrics & tm = d->text_metrics_[bot.text()];
731 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
732 int bot_pit = bot.pit();
733 if (bot_pit > max_pit) {
734 // FIXME: Why does this happen?
735 LYXERR0("bottom pit is greater that max pit: "
736 << bot_pit << " > " << max_pit);
740 if (bot_pit == tm.first().first - 1)
741 tm.newParMetricsUp();
742 else if (bot_pit == tm.last().first + 1)
743 tm.newParMetricsDown();
745 if (tm.has(bot_pit)) {
746 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
747 BOOST_ASSERT(!pm.rows().empty());
748 // FIXME: smooth scrolling doesn't work in mathed.
749 CursorSlice const & cs = dit.innerTextSlice();
750 int offset = coordOffset(dit, dit.boundary()).y_;
751 int ypos = pm.position() + offset;
752 Dimension const & row_dim =
753 pm.getRow(cs.pos(), dit.boundary()).dimension();
754 if (ypos - row_dim.ascent() < 0)
755 scrollUp(- ypos + row_dim.ascent());
756 else if (ypos + row_dim.descent() > height_)
757 scrollDown(ypos - height_ + row_dim.descent());
758 // else, nothing to do, the cursor is already visible so we just return.
762 tm.redoParagraph(bot_pit);
763 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
764 int offset = coordOffset(dit, dit.boundary()).y_;
766 d->anchor_pit_ = bot_pit;
767 CursorSlice const & cs = dit.innerTextSlice();
768 Dimension const & row_dim =
769 pm.getRow(cs.pos(), dit.boundary()).dimension();
771 if (d->anchor_pit_ == 0)
772 d->anchor_ypos_ = offset + pm.ascent();
773 else if (d->anchor_pit_ == max_pit)
774 d->anchor_ypos_ = height_ - offset - row_dim.descent();
776 d->anchor_ypos_ = defaultRowHeight() * 2 - offset - row_dim.descent();
783 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
787 Cursor & cur = d->cursor_;
789 switch (cmd.action) {
792 flag.enabled(buffer_.undo().hasUndoStack());
795 flag.enabled(buffer_.undo().hasRedoStack());
797 case LFUN_FILE_INSERT:
798 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
799 case LFUN_FILE_INSERT_PLAINTEXT:
800 case LFUN_BOOKMARK_SAVE:
801 // FIXME: Actually, these LFUNS should be moved to Text
802 flag.enabled(cur.inTexted());
804 case LFUN_FONT_STATE:
805 case LFUN_LABEL_INSERT:
806 case LFUN_INFO_INSERT:
807 case LFUN_PARAGRAPH_GOTO:
809 case LFUN_REFERENCE_NEXT:
811 case LFUN_WORD_REPLACE:
814 case LFUN_MARK_TOGGLE:
815 case LFUN_SCREEN_RECENTER:
816 case LFUN_BIBTEX_DATABASE_ADD:
817 case LFUN_BIBTEX_DATABASE_DEL:
818 case LFUN_STATISTICS:
819 case LFUN_NEXT_INSET_TOGGLE:
823 case LFUN_LABEL_GOTO: {
824 flag.enabled(!cmd.argument().empty()
825 || getInsetByCode<InsetRef>(cur, REF_CODE));
829 case LFUN_CHANGES_TRACK:
831 flag.setOnOff(buffer_.params().trackChanges);
834 case LFUN_CHANGES_OUTPUT:
836 flag.setOnOff(buffer_.params().outputChanges);
839 case LFUN_CHANGES_MERGE:
840 case LFUN_CHANGE_NEXT:
841 case LFUN_ALL_CHANGES_ACCEPT:
842 case LFUN_ALL_CHANGES_REJECT:
843 // TODO: context-sensitive enabling of LFUNs
844 // In principle, these command should only be enabled if there
845 // is a change in the document. However, without proper
846 // optimizations, this will inevitably result in poor performance.
850 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
851 flag.setOnOff(buffer_.params().compressed);
855 case LFUN_BUFFER_TOGGLE_EMBEDDING: {
856 flag.setOnOff(buffer_.params().embedded);
861 case LFUN_SCREEN_DOWN:
866 // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
867 // everywhere else before this can enabled:
868 case LFUN_SCREEN_UP_SELECT:
869 case LFUN_SCREEN_DOWN_SELECT:
873 case LFUN_LAYOUT_TABULAR:
874 flag.enabled(cur.innerInsetOfType(TABULAR_CODE));
878 case LFUN_LAYOUT_PARAGRAPH:
879 flag.enabled(cur.inset().forceDefaultParagraphs(cur.idx()));
882 case LFUN_INSET_SETTINGS: {
883 InsetCode code = cur.inset().lyxCode();
887 enable = cmd.argument() == "tabular";
890 enable = cmd.argument() == "ert";
893 enable = cmd.argument() == "float";
896 enable = cmd.argument() == "wrap";
899 enable = cmd.argument() == "note";
902 enable = cmd.argument() == "branch";
905 enable = cmd.argument() == "box";
908 enable = cmd.argument() == "listings";
913 flag.enabled(enable);
917 case LFUN_DIALOG_SHOW_NEW_INSET:
918 flag.enabled(cur.inset().lyxCode() != ERT_CODE &&
919 cur.inset().lyxCode() != LISTINGS_CODE);
920 if (cur.inset().lyxCode() == CAPTION_CODE) {
922 if (cur.inset().getStatus(cur, cmd, flag))
935 bool BufferView::dispatch(FuncRequest const & cmd)
937 //lyxerr << [ cmd = " << cmd << "]" << endl;
939 // Make sure that the cached BufferView is correct.
940 LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
941 << " arg[" << to_utf8(cmd.argument()) << ']'
942 << " x[" << cmd.x << ']'
943 << " y[" << cmd.y << ']'
944 << " button[" << cmd.button() << ']');
946 Cursor & cur = d->cursor_;
948 switch (cmd.action) {
951 cur.message(_("Undo"));
952 cur.clearSelection();
954 cur.message(_("No further undo information"));
956 processUpdateFlags(Update::Force | Update::FitCursor);
960 cur.message(_("Redo"));
961 cur.clearSelection();
963 cur.message(_("No further redo information"));
965 processUpdateFlags(Update::Force | Update::FitCursor);
968 case LFUN_FONT_STATE:
969 cur.message(cur.currentState());
972 case LFUN_BOOKMARK_SAVE:
973 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
976 case LFUN_LABEL_GOTO: {
977 docstring label = cmd.argument();
980 getInsetByCode<InsetRef>(d->cursor_,
983 label = inset->getParam("reference");
984 // persistent=false: use temp_bookmark
994 case LFUN_PARAGRAPH_GOTO: {
995 int const id = convert<int>(to_utf8(cmd.argument()));
997 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
998 b = theBufferList().next(b)) {
1000 ParIterator par = b->getParFromID(id);
1001 if (par == b->par_iterator_end()) {
1002 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1004 LYXERR(Debug::INFO, "Paragraph " << par->id()
1005 << " found in buffer `"
1006 << b->absFileName() << "'.");
1008 if (b == &buffer_) {
1010 setCursor(makeDocIterator(par, 0));
1013 // Switch to other buffer view and resend cmd
1014 theLyXFunc().dispatch(FuncRequest(
1015 LFUN_BUFFER_SWITCH, b->absFileName()));
1016 theLyXFunc().dispatch(cmd);
1025 case LFUN_NOTE_NEXT:
1026 gotoInset(this, NOTE_CODE, false);
1029 case LFUN_REFERENCE_NEXT: {
1030 vector<InsetCode> tmp;
1031 tmp.push_back(LABEL_CODE);
1032 tmp.push_back(REF_CODE);
1033 gotoInset(this, tmp, true);
1037 case LFUN_CHANGES_TRACK:
1038 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1041 case LFUN_CHANGES_OUTPUT:
1042 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1043 if (buffer_.params().outputChanges) {
1044 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1045 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1046 LaTeXFeatures::isAvailable("xcolor");
1048 if (!dvipost && !xcolorsoul) {
1049 Alert::warning(_("Changes not shown in LaTeX output"),
1050 _("Changes will not be highlighted in LaTeX output, "
1051 "because neither dvipost nor xcolor/soul are installed.\n"
1052 "Please install these packages or redefine "
1053 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1054 } else if (!xcolorsoul) {
1055 Alert::warning(_("Changes not shown in LaTeX output"),
1056 _("Changes will not be highlighted in LaTeX output "
1057 "when using pdflatex, because xcolor and soul are not installed.\n"
1058 "Please install both packages or redefine "
1059 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1064 case LFUN_CHANGE_NEXT:
1065 findNextChange(this);
1068 case LFUN_CHANGES_MERGE:
1069 if (findNextChange(this))
1070 showDialog("changes");
1073 case LFUN_ALL_CHANGES_ACCEPT:
1074 // select complete document
1075 d->cursor_.reset(buffer_.inset());
1076 d->cursor_.selHandle(true);
1077 buffer_.text().cursorBottom(d->cursor_);
1078 // accept everything in a single step to support atomic undo
1079 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1082 case LFUN_ALL_CHANGES_REJECT:
1083 // select complete document
1084 d->cursor_.reset(buffer_.inset());
1085 d->cursor_.selHandle(true);
1086 buffer_.text().cursorBottom(d->cursor_);
1087 // reject everything in a single step to support atomic undo
1088 // Note: reject does not work recursively; the user may have to repeat the operation
1089 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1092 case LFUN_WORD_FIND:
1096 case LFUN_WORD_REPLACE: {
1097 bool has_deleted = false;
1098 if (cur.selection()) {
1099 DocIterator beg = cur.selectionBegin();
1100 DocIterator end = cur.selectionEnd();
1101 if (beg.pit() == end.pit()) {
1102 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1103 if (cur.paragraph().isDeleted(p))
1108 replace(this, cmd, has_deleted);
1113 cur.clearSelection();
1115 cur.message(from_utf8(N_("Mark off")));
1119 cur.clearSelection();
1122 cur.message(from_utf8(N_("Mark on")));
1125 case LFUN_MARK_TOGGLE:
1126 cur.clearSelection();
1129 cur.message(from_utf8(N_("Mark removed")));
1132 cur.message(from_utf8(N_("Mark set")));
1137 case LFUN_SCREEN_RECENTER:
1141 case LFUN_BIBTEX_DATABASE_ADD: {
1142 Cursor tmpcur = d->cursor_;
1143 findInset(tmpcur, BIBTEX_CODE, false);
1144 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1147 if (inset->addDatabase(to_utf8(cmd.argument())))
1148 buffer_.updateBibfilesCache();
1153 case LFUN_BIBTEX_DATABASE_DEL: {
1154 Cursor tmpcur = d->cursor_;
1155 findInset(tmpcur, BIBTEX_CODE, false);
1156 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1159 if (inset->delDatabase(to_utf8(cmd.argument())))
1160 buffer_.updateBibfilesCache();
1165 case LFUN_STATISTICS: {
1166 DocIterator from, to;
1167 if (cur.selection()) {
1168 from = cur.selectionBegin();
1169 to = cur.selectionEnd();
1171 from = doc_iterator_begin(buffer_.inset());
1172 to = doc_iterator_end(buffer_.inset());
1174 int const words = countWords(from, to);
1175 int const chars = countChars(from, to, false);
1176 int const chars_blanks = countChars(from, to, true);
1178 if (cur.selection())
1179 message = _("Statistics for the selection:");
1181 message = _("Statistics for the document:");
1184 message += bformat(_("%1$d words"), words);
1186 message += _("One word");
1188 if (chars_blanks != 1)
1189 message += bformat(_("%1$d characters (including blanks)"),
1192 message += _("One character (including blanks)");
1195 message += bformat(_("%1$d characters (excluding blanks)"),
1198 message += _("One character (excluding blanks)");
1200 Alert::information(_("Statistics"), message);
1204 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1205 // turn compression on/off
1206 buffer_.params().compressed = !buffer_.params().compressed;
1209 case LFUN_BUFFER_TOGGLE_EMBEDDING: {
1210 // turn embedding on/off
1212 buffer_.embeddedFiles().enable(!buffer_.params().embedded, buffer_);
1213 } catch (ExceptionMessage const & message) {
1214 Alert::error(message.title_, message.details_);
1219 case LFUN_NEXT_INSET_TOGGLE: {
1220 // this is the real function we want to invoke
1221 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1222 // if there is an inset at cursor, see whether it
1224 Inset * inset = cur.nextInset();
1226 if (inset->isActive()) {
1227 Cursor tmpcur = cur;
1228 tmpcur.pushBackward(*inset);
1229 inset->dispatch(tmpcur, tmpcmd);
1230 if (tmpcur.result().dispatched()) {
1233 } else if (inset->editable() == Inset::IS_EDITABLE) {
1234 inset->edit(cur, true);
1237 // if it did not work, try the underlying inset.
1238 if (!cur.result().dispatched())
1239 cur.dispatch(tmpcmd);
1241 if (!cur.result().dispatched())
1242 // It did not work too; no action needed.
1244 cur.clearSelection();
1245 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1249 case LFUN_SCREEN_UP:
1250 case LFUN_SCREEN_DOWN: {
1251 Point p = getPos(cur, cur.boundary());
1252 if (p.y_ < 0 || p.y_ > height_) {
1253 // The cursor is off-screen so recenter before proceeding.
1255 p = getPos(cur, cur.boundary());
1257 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1258 cur.reset(buffer_.inset());
1259 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1260 //FIXME: what to do with cur.x_target()?
1269 case LFUN_SCREEN_UP_SELECT:
1270 case LFUN_SCREEN_DOWN_SELECT: {
1271 // Those two are not ready yet for consumption.
1274 cur.selHandle(true);
1275 size_t initial_depth = cur.depth();
1276 Point const p = getPos(cur, cur.boundary());
1277 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1278 // FIXME: We need to verify if the cursor stayed within an inset...
1279 //cur.reset(buffer_.inset());
1280 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1282 while (cur.depth() > initial_depth) {
1285 // FIXME: we need to do a redraw again because of the selection
1286 // But no screen update is needed.
1287 d->update_strategy_ = NoScreenUpdate;
1300 docstring const BufferView::requestSelection()
1302 Cursor & cur = d->cursor_;
1304 if (!cur.selection()) {
1305 d->xsel_cache_.set = false;
1309 if (!d->xsel_cache_.set ||
1310 cur.top() != d->xsel_cache_.cursor ||
1311 cur.anchor_.top() != d->xsel_cache_.anchor)
1313 d->xsel_cache_.cursor = cur.top();
1314 d->xsel_cache_.anchor = cur.anchor_.top();
1315 d->xsel_cache_.set = cur.selection();
1316 return cur.selectionAsString(false);
1322 void BufferView::clearSelection()
1324 d->cursor_.clearSelection();
1325 // Clear the selection buffer. Otherwise a subsequent
1326 // middle-mouse-button paste would use the selection buffer,
1327 // not the more current external selection.
1328 cap::clearSelection();
1329 d->xsel_cache_.set = false;
1330 // The buffer did not really change, but this causes the
1331 // redraw we need because we cleared the selection above.
1336 void BufferView::resize(int width, int height)
1338 bool initialResize = (height_ == 0);
1340 // Update from work area
1344 // Clear the paragraph height cache.
1345 d->par_height_.clear();
1349 // view got his initial size, make sure that
1350 // the cursor has a proper position
1351 if (initialResize) {
1358 Inset const * BufferView::getCoveringInset(Text const & text,
1361 TextMetrics & tm = d->text_metrics_[&text];
1362 Inset * inset = tm.checkInsetHit(x, y);
1366 if (!inset->descendable())
1367 // No need to go further down if the inset is not
1371 size_t cell_number = inset->nargs();
1372 // Check all the inner cell.
1373 for (size_t i = 0; i != cell_number; ++i) {
1374 Text const * inner_text = inset->getText(i);
1377 Inset const * inset_deeper =
1378 getCoveringInset(*inner_text, x, y);
1380 return inset_deeper;
1388 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1390 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1392 // This is only called for mouse related events including
1393 // LFUN_FILE_OPEN generated by drag-and-drop.
1394 FuncRequest cmd = cmd0;
1397 cur.push(buffer_.inset());
1398 cur.selection() = d->cursor_.selection();
1400 // Either the inset under the cursor or the
1401 // surrounding Text will handle this event.
1403 // make sure we stay within the screen...
1404 cmd.y = min(max(cmd.y, -1), height_);
1406 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1408 // Get inset under mouse, if there is one.
1409 Inset const * covering_inset =
1410 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1411 if (covering_inset == d->last_inset_)
1412 // Same inset, no need to do anything...
1415 bool need_redraw = false;
1416 // const_cast because of setMouseHover().
1417 Inset * inset = const_cast<Inset *>(covering_inset);
1419 // Remove the hint on the last hovered inset (if any).
1420 need_redraw |= d->last_inset_->setMouseHover(false);
1422 // Highlighted the newly hovered inset (if any).
1423 need_redraw |= inset->setMouseHover(true);
1424 d->last_inset_ = inset;
1428 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1429 << cmd.x << ", " << cmd.y << ")");
1431 d->update_strategy_ = DecorationUpdate;
1433 // This event (moving without mouse click) is not passed further.
1434 // This should be changed if it is further utilized.
1439 // Build temporary cursor.
1440 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1442 // Put anchor at the same position.
1445 // Try to dispatch to an non-editable inset near this position
1446 // via the temp cursor. If the inset wishes to change the real
1447 // cursor it has to do so explicitly by using
1448 // cur.bv().cursor() = cur; (or similar)
1450 inset->dispatch(cur, cmd);
1452 // Now dispatch to the temporary cursor. If the real cursor should
1453 // be modified, the inset's dispatch has to do so explicitly.
1454 if (!cur.result().dispatched())
1457 //Do we have a selection?
1458 theSelection().haveSelection(cursor().selection());
1460 // If the command has been dispatched,
1461 if (cur.result().dispatched()
1462 // an update is asked,
1463 && cur.result().update())
1464 processUpdateFlags(cur.result().update());
1468 void BufferView::lfunScroll(FuncRequest const & cmd)
1470 string const scroll_type = cmd.getArg(0);
1471 int const scroll_step =
1472 (scroll_type == "line")? d->scrollbarParameters_.single_step
1473 : (scroll_type == "page")? d->scrollbarParameters_.page_step : 0;
1474 if (scroll_step == 0)
1476 string const scroll_quantity = cmd.getArg(1);
1477 if (scroll_quantity == "up")
1478 scrollUp(scroll_step);
1479 else if (scroll_quantity == "down")
1480 scrollDown(scroll_step);
1482 int const scroll_value = convert<int>(scroll_quantity);
1484 scroll(scroll_step * scroll_value);
1489 void BufferView::scroll(int y)
1498 void BufferView::scrollDown(int offset)
1500 Text * text = &buffer_.text();
1501 TextMetrics & tm = d->text_metrics_[text];
1502 int ymax = height_ + offset;
1504 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1505 int bottom_pos = last.second->position() + last.second->descent();
1506 if (last.first + 1 == int(text->paragraphs().size())) {
1507 if (bottom_pos <= height_)
1509 offset = min(offset, bottom_pos - height_);
1512 if (bottom_pos > ymax)
1514 tm.newParMetricsDown();
1516 d->anchor_ypos_ -= offset;
1522 void BufferView::scrollUp(int offset)
1524 Text * text = &buffer_.text();
1525 TextMetrics & tm = d->text_metrics_[text];
1526 int ymin = - offset;
1528 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1529 int top_pos = first.second->position() - first.second->ascent();
1530 if (first.first == 0) {
1533 offset = min(offset, - top_pos);
1538 tm.newParMetricsUp();
1540 d->anchor_ypos_ += offset;
1546 void BufferView::setCursorFromRow(int row)
1551 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1553 d->cursor_.reset(buffer_.inset());
1555 buffer_.text().setCursor(d->cursor_, 0, 0);
1557 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1561 void BufferView::gotoLabel(docstring const & label)
1563 for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1564 vector<docstring> labels;
1565 it->getLabelList(buffer_, labels);
1566 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1575 TextMetrics const & BufferView::textMetrics(Text const * t) const
1577 return const_cast<BufferView *>(this)->textMetrics(t);
1581 TextMetrics & BufferView::textMetrics(Text const * t)
1583 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
1584 if (tmc_it == d->text_metrics_.end()) {
1585 tmc_it = d->text_metrics_.insert(
1586 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1588 return tmc_it->second;
1592 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1595 return textMetrics(t).parMetrics(pit);
1599 int BufferView::workHeight() const
1605 void BufferView::setCursor(DocIterator const & dit)
1607 size_t const n = dit.depth();
1608 for (size_t i = 0; i < n; ++i)
1609 dit[i].inset().edit(d->cursor_, true);
1611 d->cursor_.setCursor(dit);
1612 d->cursor_.selection() = false;
1616 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1618 // Would be wrong to delete anything if we have a selection.
1619 if (cur.selection())
1622 bool need_anchor_change = false;
1623 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1624 need_anchor_change);
1626 if (need_anchor_change)
1634 updateLabels(buffer_);
1642 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1644 BOOST_ASSERT(&cur.bv() == this);
1647 // this event will clear selection so we save selection for
1648 // persistent selection
1649 cap::saveSelection(cursor());
1651 // Has the cursor just left the inset?
1652 bool badcursor = false;
1653 bool leftinset = (&d->cursor_.inset() != &cur.inset());
1655 badcursor = notifyCursorLeaves(d->cursor_, cur);
1657 // FIXME: shift-mouse selection doesn't work well across insets.
1658 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1660 // do the dEPM magic if needed
1661 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1662 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1663 // the leftinset bool would not be necessary (badcursor instead).
1664 bool update = leftinset;
1665 if (!do_selection && !badcursor && d->cursor_.inTexted())
1666 update |= checkDepm(cur, d->cursor_);
1668 // if the cursor was in an empty script inset and the new
1669 // position is in the nucleus of the inset, notifyCursorLeaves
1670 // will kill the script inset itself. So we check all the
1671 // elements of the cursor to make sure that they are correct.
1672 // For an example, see bug 2933:
1673 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1674 // The code below could maybe be moved to a DocIterator method.
1675 //lyxerr << "cur before " << cur <<endl;
1676 DocIterator dit(cur.inset());
1677 dit.push_back(cur.bottom());
1679 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1680 dit.push_back(cur[i]);
1683 //lyxerr << "5 cur after" << dit <<endl;
1685 d->cursor_.setCursor(dit);
1686 d->cursor_.boundary(cur.boundary());
1688 d->cursor_.setSelection();
1690 d->cursor_.clearSelection();
1692 d->cursor_.finishUndo();
1693 d->cursor_.setCurrentFont();
1698 void BufferView::putSelectionAt(DocIterator const & cur,
1699 int length, bool backwards)
1701 d->cursor_.clearSelection();
1707 d->cursor_.pos() += length;
1708 d->cursor_.setSelection(d->cursor_, -length);
1710 d->cursor_.setSelection(d->cursor_, length);
1715 Cursor & BufferView::cursor()
1721 Cursor const & BufferView::cursor() const
1727 pit_type BufferView::anchor_ref() const
1729 return d->anchor_pit_;
1733 bool BufferView::singleParUpdate()
1735 Text & buftext = buffer_.text();
1736 pit_type const bottom_pit = d->cursor_.bottom().pit();
1737 TextMetrics & tm = textMetrics(&buftext);
1738 int old_height = tm.parMetrics(bottom_pit).height();
1740 // In Single Paragraph mode, rebreak only
1741 // the (main text, not inset!) paragraph containing the cursor.
1742 // (if this paragraph contains insets etc., rebreaking will
1743 // recursively descend)
1744 tm.redoParagraph(bottom_pit);
1745 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
1746 if (pm.height() != old_height)
1747 // Paragraph height has changed so we cannot proceed to
1748 // the singlePar optimisation.
1751 d->update_strategy_ = SingleParUpdate;
1753 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
1754 << " y2: " << pm.position() + pm.descent()
1755 << " pit: " << bottom_pit
1756 << " singlepar: 1");
1761 void BufferView::updateMetrics()
1763 Text & buftext = buffer_.text();
1764 pit_type const npit = int(buftext.paragraphs().size());
1766 // Clear out the position cache in case of full screen redraw,
1767 d->coord_cache_.clear();
1769 // Clear out paragraph metrics to avoid having invalid metrics
1770 // in the cache from paragraphs not relayouted below
1771 // The complete text metrics will be redone.
1772 d->text_metrics_.clear();
1774 TextMetrics & tm = textMetrics(&buftext);
1776 // Rebreak anchor paragraph.
1777 tm.redoParagraph(d->anchor_pit_);
1778 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
1781 if (d->anchor_pit_ == 0) {
1782 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
1784 // Complete buffer visible? Then it's easy.
1785 if (scrollRange == 0)
1786 d->anchor_ypos_ = anchor_pm.ascent();
1788 // FIXME: Some clever handling needed to show
1789 // the _first_ paragraph up to the top if the cursor is
1790 // in the first line.
1792 anchor_pm.setPosition(d->anchor_ypos_);
1794 LYXERR(Debug::PAINTING, "metrics: "
1795 << " anchor pit = " << d->anchor_pit_
1796 << " anchor ypos = " << d->anchor_ypos_);
1798 // Redo paragraphs above anchor if necessary.
1799 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
1800 // We are now just above the anchor paragraph.
1801 pit_type pit1 = d->anchor_pit_ - 1;
1802 for (; pit1 >= 0 && y1 >= 0; --pit1) {
1803 tm.redoParagraph(pit1);
1804 ParagraphMetrics & pm = tm.par_metrics_[pit1];
1806 // Save the paragraph position in the cache.
1811 // Redo paragraphs below the anchor if necessary.
1812 int y2 = d->anchor_ypos_ + anchor_pm.descent();
1813 // We are now just below the anchor paragraph.
1814 pit_type pit2 = d->anchor_pit_ + 1;
1815 for (; pit2 < npit && y2 <= height_; ++pit2) {
1816 tm.redoParagraph(pit2);
1817 ParagraphMetrics & pm = tm.par_metrics_[pit2];
1819 // Save the paragraph position in the cache.
1824 LYXERR(Debug::PAINTING, "Metrics: "
1825 << " anchor pit = " << d->anchor_pit_
1826 << " anchor ypos = " << d->anchor_ypos_
1829 << " pit1 = " << pit1
1830 << " pit2 = " << pit2);
1832 d->update_strategy_ = FullScreenUpdate;
1834 if (lyxerr.debugging(Debug::WORKAREA)) {
1835 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
1836 d->coord_cache_.dump();
1841 void BufferView::insertLyXFile(FileName const & fname)
1843 BOOST_ASSERT(d->cursor_.inTexted());
1845 // Get absolute path of file and add ".lyx"
1846 // to the filename if necessary
1847 FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
1849 docstring const disp_fn = makeDisplayPath(filename.absFilename());
1850 // emit message signal.
1851 message(bformat(_("Inserting document %1$s..."), disp_fn));
1854 Buffer buf("", false);
1855 if (buf.loadLyXFile(filename)) {
1856 ErrorList & el = buffer_.errorList("Parse");
1857 // Copy the inserted document error list into the current buffer one.
1858 el = buf.errorList("Parse");
1859 buffer_.undo().recordUndo(d->cursor_);
1860 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
1861 buf.params().getTextClassPtr(), el);
1862 res = _("Document %1$s inserted.");
1864 res = _("Could not insert document %1$s");
1869 // emit message signal.
1870 message(bformat(res, disp_fn));
1871 buffer_.errors("Parse");
1875 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1881 // Addup contribution of nested insets, from inside to outside,
1882 // keeping the outer paragraph for a special handling below
1883 for (size_t i = dit.depth() - 1; i >= 1; --i) {
1884 CursorSlice const & sl = dit[i];
1888 // get relative position inside sl.inset()
1889 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
1891 // Make relative position inside of the edited inset relative to sl.inset()
1895 // In case of an RTL inset, the edited inset will be positioned to the left
1898 bool boundary_i = boundary && i + 1 == dit.depth();
1899 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
1904 // remember width for the case that sl.inset() is positioned in an RTL inset
1905 if (i && dit[i - 1].text()) {
1906 // If this Inset is inside a Text Inset, retrieve the Dimension
1907 // from the containing text instead of using Inset::dimension() which
1908 // might not be implemented.
1909 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
1910 // elimination of Inset::dim_ cache. This coordOffset() method needs
1911 // to be rewritten in light of the new design.
1912 Dimension const & dim = parMetrics(dit[i - 1].text(),
1913 dit[i - 1].pit()).insetDimension(&sl.inset());
1916 Dimension const dim = sl.inset().dimension(*this);
1920 //lyxerr << "Cursor::getPos, i: "
1921 // << i << " x: " << xx << " y: " << y << endl;
1924 // Add contribution of initial rows of outermost paragraph
1925 CursorSlice const & sl = dit[0];
1926 TextMetrics const & tm = textMetrics(sl.text());
1927 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
1928 BOOST_ASSERT(!pm.rows().empty());
1929 y -= pm.rows()[0].ascent();
1931 // FIXME: document this mess
1933 if (sl.pos() > 0 && dit.depth() == 1) {
1935 if (pos && boundary)
1937 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
1938 rend = pm.pos2row(pos);
1940 rend = pm.pos2row(sl.pos());
1942 size_t rend = pm.pos2row(sl.pos());
1944 for (size_t rit = 0; rit != rend; ++rit)
1945 y += pm.rows()[rit].height();
1946 y += pm.rows()[rend].ascent();
1948 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
1950 // Make relative position from the nested inset now bufferview absolute.
1951 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
1954 // In the RTL case place the nested inset at the left of the cursor in
1955 // the outer paragraph
1956 bool boundary_1 = boundary && 1 == dit.depth();
1957 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
1965 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
1967 CursorSlice const & bot = dit.bottom();
1968 TextMetrics const & tm = textMetrics(bot.text());
1969 if (!tm.has(bot.pit()))
1970 return Point(-1, -1);
1972 Point p = coordOffset(dit, boundary); // offset from outer paragraph
1973 p.y_ += tm.parMetrics(bot.pit()).position();
1978 void BufferView::draw(frontend::Painter & pain)
1980 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
1981 Text & text = buffer_.text();
1982 TextMetrics const & tm = d->text_metrics_[&text];
1983 int const y = tm.first().second->position();
1984 PainterInfo pi(this, pain);
1986 switch (d->update_strategy_) {
1988 case NoScreenUpdate:
1989 // If no screen painting is actually needed, only some the different
1990 // coordinates of insets and paragraphs needs to be updated.
1991 pi.full_repaint = true;
1992 pi.pain.setDrawingEnabled(false);
1996 case SingleParUpdate:
1997 pi.full_repaint = false;
1998 // In general, only the current row of the outermost paragraph
1999 // will be redrawn. Particular cases where selection spans
2000 // multiple paragraph are correctly detected in TextMetrics.
2004 case DecorationUpdate:
2005 // FIXME: We should also distinguish DecorationUpdate to avoid text
2006 // drawing if possible. This is not possible to do easily right now
2007 // because of the single backing pixmap.
2009 case FullScreenUpdate:
2010 // The whole screen, including insets, will be refreshed.
2011 pi.full_repaint = true;
2013 // Clear background.
2014 pain.fillRectangle(0, 0, width_, height_,
2015 buffer_.inset().backgroundColor());
2020 // and possibly grey out below
2021 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2022 int const y2 = lastpm.second->position() + lastpm.second->descent();
2024 pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
2027 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
2029 // The scrollbar needs an update.
2032 // Normalize anchor for next time
2033 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2034 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2035 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2036 ParagraphMetrics const & pm = tm.parMetrics(pit);
2037 if (pm.position() + pm.descent() > 0) {
2038 d->anchor_pit_ = pit;
2039 d->anchor_ypos_ = pm.position();
2043 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2044 << " anchor ypos = " << d->anchor_ypos_);
2048 void BufferView::message(docstring const & msg)
2051 d->gui_->message(msg);
2055 void BufferView::showDialog(string const & name)
2058 d->gui_->showDialog(name, string());
2062 void BufferView::showDialog(string const & name,
2063 string const & data, Inset * inset)
2066 d->gui_->showDialog(name, data, inset);
2070 void BufferView::updateDialog(string const & name, string const & data)
2073 d->gui_->updateDialog(name, data);
2077 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2083 // FIXME: Move this out of BufferView again
2084 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2086 if (!fname.isReadableFile()) {
2087 docstring const error = from_ascii(strerror(errno));
2088 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2089 docstring const text =
2090 bformat(_("Could not read the specified document\n"
2091 "%1$s\ndue to the error: %2$s"), file, error);
2092 Alert::error(_("Could not read file"), text);
2096 if (!fname.isReadableFile()) {
2097 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2098 docstring const text =
2099 bformat(_("%1$s\n is not readable."), file);
2100 Alert::error(_("Could not open file"), text);
2104 // FIXME UNICODE: We don't know the encoding of the file
2105 docstring file_content = fname.fileContents("UTF-8");
2106 if (file_content.empty()) {
2107 Alert::error(_("Reading not UTF-8 encoded file"),
2108 _("The file is not UTF-8 encoded.\n"
2109 "It will be read as local 8Bit-encoded.\n"
2110 "If this does not give the correct result\n"
2111 "then please change the encoding of the file\n"
2112 "to UTF-8 with a program other than LyX.\n"));
2113 file_content = fname.fileContents("local8bit");
2116 return normalize_c(file_content);
2120 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2122 docstring const tmpstr = contentsOfPlaintextFile(f);
2127 Cursor & cur = cursor();
2128 cap::replaceSelection(cur);
2129 buffer_.undo().recordUndo(cur);
2131 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2133 cur.innerText()->insertStringAsLines(cur, tmpstr);