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/FileFilterList.h"
73 #include "support/filetools.h"
74 #include "support/gettext.h"
75 #include "support/lstrings.h"
76 #include "support/Package.h"
77 #include "support/types.h"
86 using namespace lyx::support;
90 namespace Alert = frontend::Alert;
94 /// Return an inset of this class if it exists at the current cursor position
96 T * getInsetByCode(Cursor const & cur, InsetCode code)
99 Inset * inset = it.nextInset();
100 if (inset && inset->lyxCode() == code)
101 return static_cast<T*>(inset);
106 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
109 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
110 docstring const & contents)
112 DocIterator tmpdit = dit;
115 Inset const * inset = tmpdit.nextInset();
117 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
118 && (contents.empty() ||
119 static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
123 tmpdit.forwardInset();
130 /// Looks for next inset with one of the given codes.
131 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
135 DocIterator tmpdit = dit;
136 tmpdit.forwardInset();
141 Inset const * inset = tmpdit.nextInset();
143 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
144 contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
148 if (!findNextInset(tmpdit, codes, contents)) {
149 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
150 tmpdit = doc_iterator_begin(tmpdit.bottom().inset());
151 if (!findNextInset(tmpdit, codes, contents))
162 /// Looks for next inset with the given code
163 void findInset(DocIterator & dit, InsetCode code, bool same_content)
165 findInset(dit, vector<InsetCode>(1, code), same_content);
169 /// Moves cursor to the next inset with one of the given codes.
170 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
173 Cursor tmpcur = bv->cursor();
174 if (!findInset(tmpcur, codes, same_content)) {
175 bv->cursor().message(_("No more insets"));
179 tmpcur.clearSelection();
180 bv->setCursor(tmpcur);
185 /// Moves cursor to the next inset with given code.
186 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
188 gotoInset(bv, vector<InsetCode>(1, code), same_content);
192 /// A map from a Text to the associated text metrics
193 typedef map<Text const *, TextMetrics> TextMetricsCache;
195 enum ScreenUpdateStrategy {
205 /////////////////////////////////////////////////////////////////////
209 /////////////////////////////////////////////////////////////////////
211 struct BufferView::Private
213 Private(BufferView & bv): wh_(0), cursor_(bv),
214 anchor_pit_(0), anchor_ypos_(0),
215 last_inset_(0), gui_(0)
219 ScrollbarParameters scrollbarParameters_;
221 ScreenUpdateStrategy update_strategy_;
223 CoordCache coord_cache_;
225 /// Estimated average par height for scrollbar.
227 /// this is used to handle XSelection events in the right manner.
236 pit_type anchor_pit_;
240 vector<int> par_height_;
242 /// keyboard mapping object.
245 /// last visited inset.
246 /** kept to send setMouseHover(false).
247 * Not owned, so don't delete.
251 mutable TextMetricsCache text_metrics_;
254 /** Not owned, so don't delete.
256 frontend::GuiBufferViewDelegate * gui_;
260 BufferView::BufferView(Buffer & buf)
261 : width_(0), height_(0), buffer_(buf), d(new Private(*this))
263 d->xsel_cache_.set = false;
264 d->intl_.initKeyMapper(lyxrc.use_kbmap);
266 d->cursor_.push(buffer_.inset());
267 d->cursor_.resetAnchor();
268 d->cursor_.setCurrentFont();
270 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
271 graphics::Previews::get().generateBufferPreviews(buffer_);
275 BufferView::~BufferView()
277 // current buffer is going to be switched-off, save cursor pos
278 // Ideally, the whole cursor stack should be saved, but session
279 // currently can only handle bottom (whole document) level pit and pos.
280 // That is to say, if a cursor is in a nested inset, it will be
281 // restore to the left of the top level inset.
282 LastFilePosSection::FilePos fp;
283 fp.pit = d->cursor_.bottom().pit();
284 fp.pos = d->cursor_.bottom().pos();
285 LyX::ref().session().lastFilePos().save(buffer_.fileName(), fp);
291 Intl & BufferView::getIntl()
297 Intl const & BufferView::getIntl() const
303 CoordCache & BufferView::coordCache()
305 return d->coord_cache_;
309 CoordCache const & BufferView::coordCache() const
311 return d->coord_cache_;
315 Buffer & BufferView::buffer()
321 Buffer const & BufferView::buffer() const
327 bool BufferView::fitCursor()
329 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
330 frontend::FontMetrics const & fm =
331 theFontMetrics(d->cursor_.getFont().fontInfo());
332 int const asc = fm.maxAscent();
333 int const des = fm.maxDescent();
334 Point const p = getPos(d->cursor_, d->cursor_.boundary());
335 if (p.y_ - asc >= 0 && p.y_ + des < height_)
342 void BufferView::processUpdateFlags(Update::flags flags)
344 // last_inset_ points to the last visited inset. This pointer may become
345 // invalid because of keyboard editing. Since all such operations
346 // causes screen update(), I reset last_inset_ to avoid such a problem.
348 // This is close to a hot-path.
349 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
350 << "[fitcursor = " << (flags & Update::FitCursor)
351 << ", forceupdate = " << (flags & Update::Force)
352 << ", singlepar = " << (flags & Update::SinglePar)
353 << "] buffer: " << &buffer_);
355 buffer_.updateMacros();
357 // Now do the first drawing step if needed. This consists on updating
358 // the CoordCache in updateMetrics().
359 // The second drawing step is done in WorkArea::redraw() if needed.
361 // Case when no explicit update is requested.
363 // no need to redraw anything.
364 d->update_strategy_ = NoScreenUpdate;
368 if (flags == Update::Decoration) {
369 d->update_strategy_ = DecorationUpdate;
374 if (flags == Update::FitCursor
375 || flags == (Update::Decoration | Update::FitCursor)) {
376 // tell the frontend to update the screen if needed.
381 if (flags & Update::Decoration) {
382 d->update_strategy_ = DecorationUpdate;
386 // no screen update is needed.
387 d->update_strategy_ = NoScreenUpdate;
391 bool const full_metrics = flags & Update::Force || !singleParUpdate();
394 // We have to update the full screen metrics.
397 if (!(flags & Update::FitCursor)) {
398 // Nothing to do anymore. Trigger a redraw and return
403 // updateMetrics() does not update paragraph position
404 // This is done at draw() time. So we need a redraw!
408 // The cursor is off screen so ensure it is visible.
415 void BufferView::updateScrollbar()
420 // We prefer fixed size line scrolling.
421 d->scrollbarParameters_.single_step = defaultRowHeight();
422 // We prefer full screen page scrolling.
423 d->scrollbarParameters_.page_step = height_;
425 Text & t = buffer_.text();
426 TextMetrics & tm = d->text_metrics_[&t];
428 LYXERR(Debug::GUI, " Updating scrollbar: height: "
429 << t.paragraphs().size()
430 << " curr par: " << d->cursor_.bottom().pit()
431 << " default height " << defaultRowHeight());
433 int const parsize = int(t.paragraphs().size());
434 if (d->par_height_.size() != parsize) {
435 d->par_height_.clear();
436 // FIXME: We assume a default paragraph height of 2 rows. This
437 // should probably be pondered with the screen width.
438 d->par_height_.resize(parsize, defaultRowHeight() * 2);
441 // Look at paragraph heights on-screen
442 pair<pit_type, ParagraphMetrics const *> first = tm.first();
443 pair<pit_type, ParagraphMetrics const *> last = tm.last();
444 for (pit_type pit = first.first; pit <= last.first; ++pit) {
445 d->par_height_[pit] = tm.parMetrics(pit).height();
446 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
447 << d->par_height_[pit]);
450 int top_pos = first.second->position() - first.second->ascent();
451 int bottom_pos = last.second->position() + last.second->descent();
452 bool first_visible = first.first == 0 && top_pos >= 0;
453 bool last_visible = last.first == parsize - 1 && bottom_pos <= height_;
454 if (first_visible && last_visible) {
455 d->scrollbarParameters_.min = 0;
456 d->scrollbarParameters_.max = 0;
460 d->scrollbarParameters_.min = top_pos;
461 for (size_t i = 0; i != first.first; ++i)
462 d->scrollbarParameters_.min -= d->par_height_[i];
463 d->scrollbarParameters_.max = bottom_pos;
464 for (size_t i = last.first + 1; i != parsize; ++i)
465 d->scrollbarParameters_.max += d->par_height_[i];
467 d->scrollbarParameters_.position = 0;
468 // The reference is the top position so we remove one page.
469 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
473 ScrollbarParameters const & BufferView::scrollbarParameters() const
475 return d->scrollbarParameters_;
479 docstring BufferView::toolTip(int x, int y) const
481 // Get inset under mouse, if there is one.
482 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
484 // No inset, no tooltip...
486 return covering_inset->toolTip(*this, x, y);
490 docstring BufferView::contextMenu(int x, int y) const
492 // Get inset under mouse, if there is one.
493 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
495 return covering_inset->contextMenu(*this, x, y);
497 // FIXME: Do something more elaborate here.
498 return from_ascii("edit");
502 void BufferView::scrollDocView(int value)
504 int const offset = value - d->scrollbarParameters_.position;
505 // If the offset is less than 2 screen height, prefer to scroll instead.
506 if (abs(offset) <= 2 * height_) {
511 // cut off at the top
512 if (value <= d->scrollbarParameters_.min) {
513 DocIterator dit = doc_iterator_begin(buffer_.inset());
515 LYXERR(Debug::SCROLLING, "scroll to top");
519 // cut off at the bottom
520 if (value >= d->scrollbarParameters_.max) {
521 DocIterator dit = doc_iterator_end(buffer_.inset());
524 LYXERR(Debug::SCROLLING, "scroll to bottom");
528 // find paragraph at target position
529 int par_pos = d->scrollbarParameters_.min;
531 for (; i != d->par_height_.size(); ++i) {
532 par_pos += d->par_height_[i];
533 if (par_pos >= value)
537 if (par_pos < value) {
538 // It seems we didn't find the correct pit so stay on the safe side and
540 LYXERR0("scrolling position not found!");
541 scrollDocView(d->scrollbarParameters_.max);
545 DocIterator dit = doc_iterator_begin(buffer_.inset());
547 LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
552 // FIXME: this method is not working well.
553 void BufferView::setCursorFromScrollbar()
555 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
557 int const height = 2 * defaultRowHeight();
558 int const first = height;
559 int const last = height_ - height;
560 Cursor & cur = d->cursor_;
562 switch (cursorStatus(cur)) {
564 // We reset the cursor because cursorStatus() does not
565 // work when the cursor is within mathed.
566 cur.reset(buffer_.inset());
567 tm.setCursorFromCoordinates(cur, 0, first);
568 cur.clearSelection();
571 // We reset the cursor because cursorStatus() does not
572 // work when the cursor is within mathed.
573 cur.reset(buffer_.inset());
574 tm.setCursorFromCoordinates(cur, 0, last);
575 cur.clearSelection();
578 int const y = getPos(cur, cur.boundary()).y_;
579 int const newy = min(last, max(y, first));
581 cur.reset(buffer_.inset());
582 tm.setCursorFromCoordinates(cur, 0, newy);
588 Change const BufferView::getCurrentChange() const
590 if (!d->cursor_.selection())
591 return Change(Change::UNCHANGED);
593 DocIterator dit = d->cursor_.selectionBegin();
594 return dit.paragraph().lookupChange(dit.pos());
598 // this could be used elsewhere as well?
599 // FIXME: This does not work within mathed!
600 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
602 Point const p = getPos(dit, dit.boundary());
605 if (p.y_ > workHeight())
611 void BufferView::saveBookmark(unsigned int idx)
613 // tenatively save bookmark, id and pos will be used to
614 // acturately locate a bookmark in a 'live' lyx session.
615 // pit and pos will be updated with bottom level pit/pos
617 LyX::ref().session().bookmarks().save(
619 d->cursor_.bottom().pit(),
620 d->cursor_.bottom().pos(),
621 d->cursor_.paragraph().id(),
626 // emit message signal.
627 message(_("Save bookmark"));
631 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
632 int top_id, pos_type top_pos)
634 bool success = false;
637 d->cursor_.clearSelection();
639 // if a valid par_id is given, try it first
640 // This is the case for a 'live' bookmark when unique paragraph ID
641 // is used to track bookmarks.
643 ParIterator par = buffer_.getParFromID(top_id);
644 if (par != buffer_.par_iterator_end()) {
645 doc_it = makeDocIterator(par, min(par->size(), top_pos));
646 // Some slices of the iterator may not be
647 // reachable (e.g. closed collapsable inset)
648 // so the dociterator may need to be
649 // shortened. Otherwise, setCursor may crash
650 // lyx when the cursor can not be set to these
652 size_t const n = doc_it.depth();
653 for (size_t i = 0; i < n; ++i)
654 if (doc_it[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
662 // if top_id == 0, or searching through top_id failed
663 // This is the case for a 'restored' bookmark when only bottom
664 // (document level) pit was saved. Because of this, bookmark
665 // restoration is inaccurate. If a bookmark was within an inset,
666 // it will be restored to the left of the outmost inset that contains
668 if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
669 doc_it = doc_iterator_begin(buffer_.inset());
670 doc_it.pit() = bottom_pit;
671 doc_it.pos() = min(bottom_pos, doc_it.paragraph().size());
676 // Note: only bottom (document) level pit is set.
678 // set the current font.
679 d->cursor_.setCurrentFont();
680 // To center the screen on this new position we need the
681 // paragraph position which is computed at draw() time.
682 // So we need a redraw!
692 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
694 if (lyxrc.rtl_support) {
695 if (d->cursor_.real_current_font.isRightToLeft()) {
696 if (d->intl_.keymap == Intl::PRIMARY)
697 d->intl_.keyMapSec();
699 if (d->intl_.keymap == Intl::SECONDARY)
700 d->intl_.keyMapPrim();
704 d->intl_.getTransManager().translateAndInsert(c, t, cur);
708 int BufferView::workWidth() const
714 void BufferView::showCursor()
716 showCursor(d->cursor_);
720 void BufferView::showCursor(DocIterator const & dit)
722 // We are not properly started yet, delay until resizing is
727 LYXERR(Debug::SCROLLING, "recentering!");
729 CursorSlice const & bot = dit.bottom();
730 TextMetrics & tm = d->text_metrics_[bot.text()];
732 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
733 int bot_pit = bot.pit();
734 if (bot_pit > max_pit) {
735 // FIXME: Why does this happen?
736 LYXERR0("bottom pit is greater that max pit: "
737 << bot_pit << " > " << max_pit);
741 if (bot_pit == tm.first().first - 1)
742 tm.newParMetricsUp();
743 else if (bot_pit == tm.last().first + 1)
744 tm.newParMetricsDown();
746 if (tm.has(bot_pit)) {
747 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
748 BOOST_ASSERT(!pm.rows().empty());
749 // FIXME: smooth scrolling doesn't work in mathed.
750 CursorSlice const & cs = dit.innerTextSlice();
751 int offset = coordOffset(dit, dit.boundary()).y_;
752 int ypos = pm.position() + offset;
753 Dimension const & row_dim =
754 pm.getRow(cs.pos(), dit.boundary()).dimension();
755 if (ypos - row_dim.ascent() < 0)
756 scrollUp(- ypos + row_dim.ascent());
757 else if (ypos + row_dim.descent() > height_)
758 scrollDown(ypos - height_ + row_dim.descent());
759 // else, nothing to do, the cursor is already visible so we just return.
763 tm.redoParagraph(bot_pit);
764 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
765 int offset = coordOffset(dit, dit.boundary()).y_;
767 d->anchor_pit_ = bot_pit;
768 CursorSlice const & cs = dit.innerTextSlice();
769 Dimension const & row_dim =
770 pm.getRow(cs.pos(), dit.boundary()).dimension();
772 if (d->anchor_pit_ == 0)
773 d->anchor_ypos_ = offset + pm.ascent();
774 else if (d->anchor_pit_ == max_pit)
775 d->anchor_ypos_ = height_ - offset - row_dim.descent();
777 d->anchor_ypos_ = defaultRowHeight() * 2 - offset - row_dim.descent();
784 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
788 Cursor & cur = d->cursor_;
790 switch (cmd.action) {
793 flag.enabled(buffer_.undo().hasUndoStack());
796 flag.enabled(buffer_.undo().hasRedoStack());
798 case LFUN_FILE_INSERT:
799 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
800 case LFUN_FILE_INSERT_PLAINTEXT:
801 case LFUN_BOOKMARK_SAVE:
802 // FIXME: Actually, these LFUNS should be moved to Text
803 flag.enabled(cur.inTexted());
805 case LFUN_FONT_STATE:
806 case LFUN_LABEL_INSERT:
807 case LFUN_INFO_INSERT:
808 case LFUN_PARAGRAPH_GOTO:
810 case LFUN_REFERENCE_NEXT:
812 case LFUN_WORD_REPLACE:
815 case LFUN_MARK_TOGGLE:
816 case LFUN_SCREEN_RECENTER:
817 case LFUN_BIBTEX_DATABASE_ADD:
818 case LFUN_BIBTEX_DATABASE_DEL:
819 case LFUN_STATISTICS:
820 case LFUN_NEXT_INSET_TOGGLE:
824 case LFUN_LABEL_GOTO: {
825 flag.enabled(!cmd.argument().empty()
826 || getInsetByCode<InsetRef>(cur, REF_CODE));
830 case LFUN_CHANGES_TRACK:
832 flag.setOnOff(buffer_.params().trackChanges);
835 case LFUN_CHANGES_OUTPUT:
837 flag.setOnOff(buffer_.params().outputChanges);
840 case LFUN_CHANGES_MERGE:
841 case LFUN_CHANGE_NEXT:
842 case LFUN_ALL_CHANGES_ACCEPT:
843 case LFUN_ALL_CHANGES_REJECT:
844 // TODO: context-sensitive enabling of LFUNs
845 // In principle, these command should only be enabled if there
846 // is a change in the document. However, without proper
847 // optimizations, this will inevitably result in poor performance.
851 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
852 flag.setOnOff(buffer_.params().compressed);
856 case LFUN_BUFFER_TOGGLE_EMBEDDING: {
857 flag.setOnOff(buffer_.params().embedded);
862 case LFUN_SCREEN_DOWN:
867 // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
868 // everywhere else before this can enabled:
869 case LFUN_SCREEN_UP_SELECT:
870 case LFUN_SCREEN_DOWN_SELECT:
874 case LFUN_LAYOUT_TABULAR:
875 flag.enabled(cur.innerInsetOfType(TABULAR_CODE));
879 case LFUN_LAYOUT_PARAGRAPH:
880 flag.enabled(cur.inset().forceDefaultParagraphs(cur.idx()));
883 case LFUN_INSET_SETTINGS: {
884 InsetCode code = cur.inset().lyxCode();
888 enable = cmd.argument() == "tabular";
891 enable = cmd.argument() == "ert";
894 enable = cmd.argument() == "float";
897 enable = cmd.argument() == "wrap";
900 enable = cmd.argument() == "note";
903 enable = cmd.argument() == "branch";
906 enable = cmd.argument() == "box";
909 enable = cmd.argument() == "listings";
914 flag.enabled(enable);
918 case LFUN_DIALOG_SHOW_NEW_INSET:
919 flag.enabled(cur.inset().lyxCode() != ERT_CODE &&
920 cur.inset().lyxCode() != LISTINGS_CODE);
921 if (cur.inset().lyxCode() == CAPTION_CODE) {
923 if (cur.inset().getStatus(cur, cmd, flag))
936 bool BufferView::dispatch(FuncRequest const & cmd)
938 //lyxerr << [ cmd = " << cmd << "]" << endl;
940 // Make sure that the cached BufferView is correct.
941 LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
942 << " arg[" << to_utf8(cmd.argument()) << ']'
943 << " x[" << cmd.x << ']'
944 << " y[" << cmd.y << ']'
945 << " button[" << cmd.button() << ']');
947 Cursor & cur = d->cursor_;
949 switch (cmd.action) {
952 cur.message(_("Undo"));
953 cur.clearSelection();
955 cur.message(_("No further undo information"));
957 processUpdateFlags(Update::Force | Update::FitCursor);
961 cur.message(_("Redo"));
962 cur.clearSelection();
964 cur.message(_("No further redo information"));
966 processUpdateFlags(Update::Force | Update::FitCursor);
969 case LFUN_FONT_STATE:
970 cur.message(cur.currentState());
973 case LFUN_BOOKMARK_SAVE:
974 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
977 case LFUN_LABEL_GOTO: {
978 docstring label = cmd.argument();
981 getInsetByCode<InsetRef>(d->cursor_,
984 label = inset->getParam("reference");
985 // persistent=false: use temp_bookmark
995 case LFUN_PARAGRAPH_GOTO: {
996 int const id = convert<int>(to_utf8(cmd.argument()));
998 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
999 b = theBufferList().next(b)) {
1001 ParIterator par = b->getParFromID(id);
1002 if (par == b->par_iterator_end()) {
1003 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1005 LYXERR(Debug::INFO, "Paragraph " << par->id()
1006 << " found in buffer `"
1007 << b->absFileName() << "'.");
1009 if (b == &buffer_) {
1011 setCursor(makeDocIterator(par, 0));
1014 // Switch to other buffer view and resend cmd
1015 theLyXFunc().dispatch(FuncRequest(
1016 LFUN_BUFFER_SWITCH, b->absFileName()));
1017 theLyXFunc().dispatch(cmd);
1026 case LFUN_NOTE_NEXT:
1027 gotoInset(this, NOTE_CODE, false);
1030 case LFUN_REFERENCE_NEXT: {
1031 vector<InsetCode> tmp;
1032 tmp.push_back(LABEL_CODE);
1033 tmp.push_back(REF_CODE);
1034 gotoInset(this, tmp, true);
1038 case LFUN_CHANGES_TRACK:
1039 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1042 case LFUN_CHANGES_OUTPUT:
1043 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1044 if (buffer_.params().outputChanges) {
1045 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1046 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1047 LaTeXFeatures::isAvailable("xcolor");
1049 if (!dvipost && !xcolorsoul) {
1050 Alert::warning(_("Changes not shown in LaTeX output"),
1051 _("Changes will not be highlighted in LaTeX output, "
1052 "because neither dvipost nor xcolor/soul are installed.\n"
1053 "Please install these packages or redefine "
1054 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1055 } else if (!xcolorsoul) {
1056 Alert::warning(_("Changes not shown in LaTeX output"),
1057 _("Changes will not be highlighted in LaTeX output "
1058 "when using pdflatex, because xcolor and soul are not installed.\n"
1059 "Please install both packages or redefine "
1060 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1065 case LFUN_CHANGE_NEXT:
1066 findNextChange(this);
1069 case LFUN_CHANGES_MERGE:
1070 if (findNextChange(this))
1071 showDialog("changes");
1074 case LFUN_ALL_CHANGES_ACCEPT:
1075 // select complete document
1076 d->cursor_.reset(buffer_.inset());
1077 d->cursor_.selHandle(true);
1078 buffer_.text().cursorBottom(d->cursor_);
1079 // accept everything in a single step to support atomic undo
1080 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1083 case LFUN_ALL_CHANGES_REJECT:
1084 // select complete document
1085 d->cursor_.reset(buffer_.inset());
1086 d->cursor_.selHandle(true);
1087 buffer_.text().cursorBottom(d->cursor_);
1088 // reject everything in a single step to support atomic undo
1089 // Note: reject does not work recursively; the user may have to repeat the operation
1090 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1093 case LFUN_WORD_FIND:
1097 case LFUN_WORD_REPLACE: {
1098 bool has_deleted = false;
1099 if (cur.selection()) {
1100 DocIterator beg = cur.selectionBegin();
1101 DocIterator end = cur.selectionEnd();
1102 if (beg.pit() == end.pit()) {
1103 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1104 if (cur.paragraph().isDeleted(p))
1109 replace(this, cmd, has_deleted);
1114 cur.clearSelection();
1116 cur.message(from_utf8(N_("Mark off")));
1120 cur.clearSelection();
1123 cur.message(from_utf8(N_("Mark on")));
1126 case LFUN_MARK_TOGGLE:
1127 cur.clearSelection();
1130 cur.message(from_utf8(N_("Mark removed")));
1133 cur.message(from_utf8(N_("Mark set")));
1138 case LFUN_SCREEN_RECENTER:
1142 case LFUN_BIBTEX_DATABASE_ADD: {
1143 Cursor tmpcur = d->cursor_;
1144 findInset(tmpcur, BIBTEX_CODE, false);
1145 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1148 if (inset->addDatabase(to_utf8(cmd.argument())))
1149 buffer_.updateBibfilesCache();
1154 case LFUN_BIBTEX_DATABASE_DEL: {
1155 Cursor tmpcur = d->cursor_;
1156 findInset(tmpcur, BIBTEX_CODE, false);
1157 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1160 if (inset->delDatabase(to_utf8(cmd.argument())))
1161 buffer_.updateBibfilesCache();
1166 case LFUN_STATISTICS: {
1167 DocIterator from, to;
1168 if (cur.selection()) {
1169 from = cur.selectionBegin();
1170 to = cur.selectionEnd();
1172 from = doc_iterator_begin(buffer_.inset());
1173 to = doc_iterator_end(buffer_.inset());
1175 int const words = countWords(from, to);
1176 int const chars = countChars(from, to, false);
1177 int const chars_blanks = countChars(from, to, true);
1179 if (cur.selection())
1180 message = _("Statistics for the selection:");
1182 message = _("Statistics for the document:");
1185 message += bformat(_("%1$d words"), words);
1187 message += _("One word");
1189 if (chars_blanks != 1)
1190 message += bformat(_("%1$d characters (including blanks)"),
1193 message += _("One character (including blanks)");
1196 message += bformat(_("%1$d characters (excluding blanks)"),
1199 message += _("One character (excluding blanks)");
1201 Alert::information(_("Statistics"), message);
1205 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1206 // turn compression on/off
1207 buffer_.params().compressed = !buffer_.params().compressed;
1210 case LFUN_BUFFER_TOGGLE_EMBEDDING: {
1211 // turn embedding on/off
1213 buffer_.embeddedFiles().enable(!buffer_.params().embedded, buffer_);
1214 } catch (ExceptionMessage const & message) {
1215 Alert::error(message.title_, message.details_);
1220 case LFUN_NEXT_INSET_TOGGLE: {
1221 // this is the real function we want to invoke
1222 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1223 // if there is an inset at cursor, see whether it
1225 Inset * inset = cur.nextInset();
1227 if (inset->isActive()) {
1228 Cursor tmpcur = cur;
1229 tmpcur.pushBackward(*inset);
1230 inset->dispatch(tmpcur, tmpcmd);
1231 if (tmpcur.result().dispatched()) {
1234 } else if (inset->editable() == Inset::IS_EDITABLE) {
1235 inset->edit(cur, true);
1238 // if it did not work, try the underlying inset.
1239 if (!cur.result().dispatched())
1240 cur.dispatch(tmpcmd);
1242 if (!cur.result().dispatched())
1243 // It did not work too; no action needed.
1245 cur.clearSelection();
1246 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1250 case LFUN_SCREEN_UP:
1251 case LFUN_SCREEN_DOWN: {
1252 Point p = getPos(cur, cur.boundary());
1253 if (p.y_ < 0 || p.y_ > height_) {
1254 // The cursor is off-screen so recenter before proceeding.
1256 p = getPos(cur, cur.boundary());
1258 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1259 cur.reset(buffer_.inset());
1260 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1261 //FIXME: what to do with cur.x_target()?
1270 case LFUN_SCREEN_UP_SELECT:
1271 case LFUN_SCREEN_DOWN_SELECT: {
1272 // Those two are not ready yet for consumption.
1275 cur.selHandle(true);
1276 size_t initial_depth = cur.depth();
1277 Point const p = getPos(cur, cur.boundary());
1278 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1279 // FIXME: We need to verify if the cursor stayed within an inset...
1280 //cur.reset(buffer_.inset());
1281 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1283 while (cur.depth() > initial_depth) {
1286 // FIXME: we need to do a redraw again because of the selection
1287 // But no screen update is needed.
1288 d->update_strategy_ = NoScreenUpdate;
1301 docstring const BufferView::requestSelection()
1303 Cursor & cur = d->cursor_;
1305 if (!cur.selection()) {
1306 d->xsel_cache_.set = false;
1310 if (!d->xsel_cache_.set ||
1311 cur.top() != d->xsel_cache_.cursor ||
1312 cur.anchor_.top() != d->xsel_cache_.anchor)
1314 d->xsel_cache_.cursor = cur.top();
1315 d->xsel_cache_.anchor = cur.anchor_.top();
1316 d->xsel_cache_.set = cur.selection();
1317 return cur.selectionAsString(false);
1323 void BufferView::clearSelection()
1325 d->cursor_.clearSelection();
1326 // Clear the selection buffer. Otherwise a subsequent
1327 // middle-mouse-button paste would use the selection buffer,
1328 // not the more current external selection.
1329 cap::clearSelection();
1330 d->xsel_cache_.set = false;
1331 // The buffer did not really change, but this causes the
1332 // redraw we need because we cleared the selection above.
1337 void BufferView::resize(int width, int height)
1339 // Update from work area
1343 // Clear the paragraph height cache.
1344 d->par_height_.clear();
1350 Inset const * BufferView::getCoveringInset(Text const & text,
1353 TextMetrics & tm = d->text_metrics_[&text];
1354 Inset * inset = tm.checkInsetHit(x, y);
1358 if (!inset->descendable())
1359 // No need to go further down if the inset is not
1363 size_t cell_number = inset->nargs();
1364 // Check all the inner cell.
1365 for (size_t i = 0; i != cell_number; ++i) {
1366 Text const * inner_text = inset->getText(i);
1369 Inset const * inset_deeper =
1370 getCoveringInset(*inner_text, x, y);
1372 return inset_deeper;
1380 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1382 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1384 // This is only called for mouse related events including
1385 // LFUN_FILE_OPEN generated by drag-and-drop.
1386 FuncRequest cmd = cmd0;
1389 cur.push(buffer_.inset());
1390 cur.selection() = d->cursor_.selection();
1392 // Either the inset under the cursor or the
1393 // surrounding Text will handle this event.
1395 // make sure we stay within the screen...
1396 cmd.y = min(max(cmd.y, -1), height_);
1398 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1400 // Get inset under mouse, if there is one.
1401 Inset const * covering_inset =
1402 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1403 if (covering_inset == d->last_inset_)
1404 // Same inset, no need to do anything...
1407 bool need_redraw = false;
1408 // const_cast because of setMouseHover().
1409 Inset * inset = const_cast<Inset *>(covering_inset);
1411 // Remove the hint on the last hovered inset (if any).
1412 need_redraw |= d->last_inset_->setMouseHover(false);
1414 // Highlighted the newly hovered inset (if any).
1415 need_redraw |= inset->setMouseHover(true);
1416 d->last_inset_ = inset;
1420 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1421 << cmd.x << ", " << cmd.y << ")");
1423 d->update_strategy_ = DecorationUpdate;
1425 // This event (moving without mouse click) is not passed further.
1426 // This should be changed if it is further utilized.
1431 // Build temporary cursor.
1432 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1434 // Put anchor at the same position.
1437 // Try to dispatch to an non-editable inset near this position
1438 // via the temp cursor. If the inset wishes to change the real
1439 // cursor it has to do so explicitly by using
1440 // cur.bv().cursor() = cur; (or similar)
1442 inset->dispatch(cur, cmd);
1444 // Now dispatch to the temporary cursor. If the real cursor should
1445 // be modified, the inset's dispatch has to do so explicitly.
1446 if (!cur.result().dispatched())
1449 //Do we have a selection?
1450 theSelection().haveSelection(cursor().selection());
1452 // If the command has been dispatched,
1453 if (cur.result().dispatched()
1454 // an update is asked,
1455 && cur.result().update())
1456 processUpdateFlags(cur.result().update());
1460 void BufferView::lfunScroll(FuncRequest const & cmd)
1462 string const scroll_type = cmd.getArg(0);
1463 int const scroll_step =
1464 (scroll_type == "line")? d->scrollbarParameters_.single_step
1465 : (scroll_type == "page")? d->scrollbarParameters_.page_step : 0;
1466 if (scroll_step == 0)
1468 string const scroll_quantity = cmd.getArg(1);
1469 if (scroll_quantity == "up")
1470 scrollUp(scroll_step);
1471 else if (scroll_quantity == "down")
1472 scrollDown(scroll_step);
1474 int const scroll_value = convert<int>(scroll_quantity);
1476 scroll(scroll_step * scroll_value);
1481 void BufferView::scroll(int y)
1490 void BufferView::scrollDown(int offset)
1492 Text * text = &buffer_.text();
1493 TextMetrics & tm = d->text_metrics_[text];
1494 int ymax = height_ + offset;
1496 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1497 int bottom_pos = last.second->position() + last.second->descent();
1498 if (last.first + 1 == int(text->paragraphs().size())) {
1499 if (bottom_pos <= height_)
1501 offset = min(offset, bottom_pos - height_);
1504 if (bottom_pos > ymax)
1506 tm.newParMetricsDown();
1508 d->anchor_ypos_ -= offset;
1514 void BufferView::scrollUp(int offset)
1516 Text * text = &buffer_.text();
1517 TextMetrics & tm = d->text_metrics_[text];
1518 int ymin = - offset;
1520 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1521 int top_pos = first.second->position() - first.second->ascent();
1522 if (first.first == 0) {
1525 offset = min(offset, - top_pos);
1530 tm.newParMetricsUp();
1532 d->anchor_ypos_ += offset;
1538 void BufferView::setCursorFromRow(int row)
1543 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1545 d->cursor_.reset(buffer_.inset());
1547 buffer_.text().setCursor(d->cursor_, 0, 0);
1549 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1553 void BufferView::gotoLabel(docstring const & label)
1555 for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1556 vector<docstring> labels;
1557 it->getLabelList(buffer_, labels);
1558 if (find(labels.begin(), labels.end(), label) != labels.end()) {
1567 TextMetrics const & BufferView::textMetrics(Text const * t) const
1569 return const_cast<BufferView *>(this)->textMetrics(t);
1573 TextMetrics & BufferView::textMetrics(Text const * t)
1575 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
1576 if (tmc_it == d->text_metrics_.end()) {
1577 tmc_it = d->text_metrics_.insert(
1578 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1580 return tmc_it->second;
1584 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1587 return textMetrics(t).parMetrics(pit);
1591 int BufferView::workHeight() const
1597 void BufferView::setCursor(DocIterator const & dit)
1599 size_t const n = dit.depth();
1600 for (size_t i = 0; i < n; ++i)
1601 dit[i].inset().edit(d->cursor_, true);
1603 d->cursor_.setCursor(dit);
1604 d->cursor_.selection() = false;
1608 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1610 // Would be wrong to delete anything if we have a selection.
1611 if (cur.selection())
1614 bool need_anchor_change = false;
1615 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1616 need_anchor_change);
1618 if (need_anchor_change)
1626 updateLabels(buffer_);
1634 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1636 BOOST_ASSERT(&cur.bv() == this);
1639 // this event will clear selection so we save selection for
1640 // persistent selection
1641 cap::saveSelection(cursor());
1643 // Has the cursor just left the inset?
1644 bool badcursor = false;
1645 bool leftinset = (&d->cursor_.inset() != &cur.inset());
1647 badcursor = notifyCursorLeaves(d->cursor_, cur);
1649 // FIXME: shift-mouse selection doesn't work well across insets.
1650 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1652 // do the dEPM magic if needed
1653 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1654 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1655 // the leftinset bool would not be necessary (badcursor instead).
1656 bool update = leftinset;
1657 if (!do_selection && !badcursor && d->cursor_.inTexted())
1658 update |= checkDepm(cur, d->cursor_);
1660 // if the cursor was in an empty script inset and the new
1661 // position is in the nucleus of the inset, notifyCursorLeaves
1662 // will kill the script inset itself. So we check all the
1663 // elements of the cursor to make sure that they are correct.
1664 // For an example, see bug 2933:
1665 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1666 // The code below could maybe be moved to a DocIterator method.
1667 //lyxerr << "cur before " << cur <<endl;
1668 DocIterator dit(cur.inset());
1669 dit.push_back(cur.bottom());
1671 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1672 dit.push_back(cur[i]);
1675 //lyxerr << "5 cur after" << dit <<endl;
1677 d->cursor_.setCursor(dit);
1678 d->cursor_.boundary(cur.boundary());
1680 d->cursor_.setSelection();
1682 d->cursor_.clearSelection();
1684 d->cursor_.finishUndo();
1685 d->cursor_.setCurrentFont();
1690 void BufferView::putSelectionAt(DocIterator const & cur,
1691 int length, bool backwards)
1693 d->cursor_.clearSelection();
1699 d->cursor_.pos() += length;
1700 d->cursor_.setSelection(d->cursor_, -length);
1702 d->cursor_.setSelection(d->cursor_, length);
1707 Cursor & BufferView::cursor()
1713 Cursor const & BufferView::cursor() const
1719 pit_type BufferView::anchor_ref() const
1721 return d->anchor_pit_;
1725 bool BufferView::singleParUpdate()
1727 Text & buftext = buffer_.text();
1728 pit_type const bottom_pit = d->cursor_.bottom().pit();
1729 TextMetrics & tm = textMetrics(&buftext);
1730 int old_height = tm.parMetrics(bottom_pit).height();
1732 // In Single Paragraph mode, rebreak only
1733 // the (main text, not inset!) paragraph containing the cursor.
1734 // (if this paragraph contains insets etc., rebreaking will
1735 // recursively descend)
1736 tm.redoParagraph(bottom_pit);
1737 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
1738 if (pm.height() != old_height)
1739 // Paragraph height has changed so we cannot proceed to
1740 // the singlePar optimisation.
1743 d->update_strategy_ = SingleParUpdate;
1745 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
1746 << " y2: " << pm.position() + pm.descent()
1747 << " pit: " << bottom_pit
1748 << " singlepar: 1");
1753 void BufferView::updateMetrics()
1755 Text & buftext = buffer_.text();
1756 pit_type const npit = int(buftext.paragraphs().size());
1758 // Clear out the position cache in case of full screen redraw,
1759 d->coord_cache_.clear();
1761 // Clear out paragraph metrics to avoid having invalid metrics
1762 // in the cache from paragraphs not relayouted below
1763 // The complete text metrics will be redone.
1764 d->text_metrics_.clear();
1766 TextMetrics & tm = textMetrics(&buftext);
1768 // Rebreak anchor paragraph.
1769 tm.redoParagraph(d->anchor_pit_);
1770 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
1771 anchor_pm.setPosition(d->anchor_ypos_);
1773 LYXERR(Debug::PAINTING, "metrics: "
1774 << " anchor pit = " << d->anchor_pit_
1775 << " anchor ypos = " << d->anchor_ypos_);
1777 // Redo paragraphs above anchor if necessary.
1778 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
1779 // We are now just above the anchor paragraph.
1780 pit_type pit1 = d->anchor_pit_ - 1;
1781 for (; pit1 >= 0 && y1 >= 0; --pit1) {
1782 tm.redoParagraph(pit1);
1783 ParagraphMetrics & pm = tm.par_metrics_[pit1];
1785 // Save the paragraph position in the cache.
1790 // Redo paragraphs below the anchor if necessary.
1791 int y2 = d->anchor_ypos_ + anchor_pm.descent();
1792 // We are now just below the anchor paragraph.
1793 pit_type pit2 = d->anchor_pit_ + 1;
1794 for (; pit2 < npit && y2 <= height_; ++pit2) {
1795 tm.redoParagraph(pit2);
1796 ParagraphMetrics & pm = tm.par_metrics_[pit2];
1798 // Save the paragraph position in the cache.
1803 LYXERR(Debug::PAINTING, "Metrics: "
1804 << " anchor pit = " << d->anchor_pit_
1805 << " anchor ypos = " << d->anchor_ypos_
1808 << " pit1 = " << pit1
1809 << " pit2 = " << pit2);
1811 d->update_strategy_ = FullScreenUpdate;
1813 if (lyxerr.debugging(Debug::WORKAREA)) {
1814 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
1815 d->coord_cache_.dump();
1820 void BufferView::insertLyXFile(FileName const & fname)
1822 BOOST_ASSERT(d->cursor_.inTexted());
1824 // Get absolute path of file and add ".lyx"
1825 // to the filename if necessary
1826 FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
1828 docstring const disp_fn = makeDisplayPath(filename.absFilename());
1829 // emit message signal.
1830 message(bformat(_("Inserting document %1$s..."), disp_fn));
1833 Buffer buf("", false);
1834 if (buf.loadLyXFile(filename)) {
1835 ErrorList & el = buffer_.errorList("Parse");
1836 // Copy the inserted document error list into the current buffer one.
1837 el = buf.errorList("Parse");
1838 buffer_.undo().recordUndo(d->cursor_);
1839 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
1840 buf.params().getTextClassPtr(), el);
1841 res = _("Document %1$s inserted.");
1843 res = _("Could not insert document %1$s");
1848 // emit message signal.
1849 message(bformat(res, disp_fn));
1850 buffer_.errors("Parse");
1854 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1860 // Addup contribution of nested insets, from inside to outside,
1861 // keeping the outer paragraph for a special handling below
1862 for (size_t i = dit.depth() - 1; i >= 1; --i) {
1863 CursorSlice const & sl = dit[i];
1867 // get relative position inside sl.inset()
1868 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
1870 // Make relative position inside of the edited inset relative to sl.inset()
1874 // In case of an RTL inset, the edited inset will be positioned to the left
1877 bool boundary_i = boundary && i + 1 == dit.depth();
1878 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
1883 // remember width for the case that sl.inset() is positioned in an RTL inset
1884 if (i && dit[i - 1].text()) {
1885 // If this Inset is inside a Text Inset, retrieve the Dimension
1886 // from the containing text instead of using Inset::dimension() which
1887 // might not be implemented.
1888 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
1889 // elimination of Inset::dim_ cache. This coordOffset() method needs
1890 // to be rewritten in light of the new design.
1891 Dimension const & dim = parMetrics(dit[i - 1].text(),
1892 dit[i - 1].pit()).insetDimension(&sl.inset());
1895 Dimension const dim = sl.inset().dimension(*this);
1899 //lyxerr << "Cursor::getPos, i: "
1900 // << i << " x: " << xx << " y: " << y << endl;
1903 // Add contribution of initial rows of outermost paragraph
1904 CursorSlice const & sl = dit[0];
1905 TextMetrics const & tm = textMetrics(sl.text());
1906 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
1907 BOOST_ASSERT(!pm.rows().empty());
1908 y -= pm.rows()[0].ascent();
1910 // FIXME: document this mess
1912 if (sl.pos() > 0 && dit.depth() == 1) {
1914 if (pos && boundary)
1916 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
1917 rend = pm.pos2row(pos);
1919 rend = pm.pos2row(sl.pos());
1921 size_t rend = pm.pos2row(sl.pos());
1923 for (size_t rit = 0; rit != rend; ++rit)
1924 y += pm.rows()[rit].height();
1925 y += pm.rows()[rend].ascent();
1927 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
1929 // Make relative position from the nested inset now bufferview absolute.
1930 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
1933 // In the RTL case place the nested inset at the left of the cursor in
1934 // the outer paragraph
1935 bool boundary_1 = boundary && 1 == dit.depth();
1936 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
1944 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
1946 CursorSlice const & bot = dit.bottom();
1947 TextMetrics const & tm = textMetrics(bot.text());
1948 if (!tm.has(bot.pit()))
1949 return Point(-1, -1);
1951 Point p = coordOffset(dit, boundary); // offset from outer paragraph
1952 p.y_ += tm.parMetrics(bot.pit()).position();
1957 void BufferView::draw(frontend::Painter & pain)
1959 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
1960 Text & text = buffer_.text();
1961 TextMetrics const & tm = d->text_metrics_[&text];
1962 int const y = tm.first().second->position();
1963 PainterInfo pi(this, pain);
1965 switch (d->update_strategy_) {
1967 case NoScreenUpdate:
1968 // If no screen painting is actually needed, only some the different
1969 // coordinates of insets and paragraphs needs to be updated.
1970 pi.full_repaint = true;
1971 pi.pain.setDrawingEnabled(false);
1975 case SingleParUpdate:
1976 pi.full_repaint = false;
1977 // In general, only the current row of the outermost paragraph
1978 // will be redrawn. Particular cases where selection spans
1979 // multiple paragraph are correctly detected in TextMetrics.
1983 case DecorationUpdate:
1984 // FIXME: We should also distinguish DecorationUpdate to avoid text
1985 // drawing if possible. This is not possible to do easily right now
1986 // because of the single backing pixmap.
1988 case FullScreenUpdate:
1989 // The whole screen, including insets, will be refreshed.
1990 pi.full_repaint = true;
1992 // Clear background.
1993 pain.fillRectangle(0, 0, width_, height_,
1994 buffer_.inset().backgroundColor());
1999 // and possibly grey out below
2000 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2001 int const y2 = lastpm.second->position() + lastpm.second->descent();
2003 pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
2006 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
2008 // The scrollbar needs an update.
2011 // Normalize anchor for next time
2012 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2013 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2014 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2015 ParagraphMetrics const & pm = tm.parMetrics(pit);
2016 if (pm.position() + pm.descent() > 0) {
2017 d->anchor_pit_ = pit;
2018 d->anchor_ypos_ = pm.position();
2022 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2023 << " anchor ypos = " << d->anchor_ypos_);
2027 void BufferView::message(docstring const & msg)
2030 d->gui_->message(msg);
2034 void BufferView::showDialog(string const & name)
2037 d->gui_->showDialog(name, string());
2041 void BufferView::showDialog(string const & name,
2042 string const & data, Inset * inset)
2045 d->gui_->showDialog(name, data, inset);
2049 void BufferView::updateDialog(string const & name, string const & data)
2052 d->gui_->updateDialog(name, data);
2056 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2062 // FIXME: Move this out of BufferView again
2063 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2065 if (!fname.isReadableFile()) {
2066 docstring const error = from_ascii(strerror(errno));
2067 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2068 docstring const text =
2069 bformat(_("Could not read the specified document\n"
2070 "%1$s\ndue to the error: %2$s"), file, error);
2071 Alert::error(_("Could not read file"), text);
2075 if (!fname.isReadableFile()) {
2076 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2077 docstring const text =
2078 bformat(_("%1$s\n is not readable."), file);
2079 Alert::error(_("Could not open file"), text);
2083 // FIXME UNICODE: We don't know the encoding of the file
2084 docstring file_content = fname.fileContents("UTF-8");
2085 if (file_content.empty()) {
2086 Alert::error(_("Reading not UTF-8 encoded file"),
2087 _("The file is not UTF-8 encoded.\n"
2088 "It will be read as local 8Bit-encoded.\n"
2089 "If this does not give the correct result\n"
2090 "then please change the encoding of the file\n"
2091 "to UTF-8 with a program other than LyX.\n"));
2092 file_content = fname.fileContents("local8bit");
2095 return normalize_c(file_content);
2099 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2101 docstring const tmpstr = contentsOfPlaintextFile(f);
2106 Cursor & cur = cursor();
2107 cap::replaceSelection(cur);
2108 buffer_.undo().recordUndo(cur);
2110 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2112 cur.innerText()->insertStringAsLines(cur, tmpstr);