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/Delegates.h"
62 #include "frontends/FontMetrics.h"
63 #include "frontends/Painter.h"
64 #include "frontends/Selection.h"
66 #include "graphics/Previews.h"
68 #include "support/convert.h"
69 #include "support/debug.h"
70 #include "support/FileFilterList.h"
71 #include "support/filetools.h"
72 #include "support/gettext.h"
73 #include "support/lstrings.h"
74 #include "support/Package.h"
75 #include "support/types.h"
84 using namespace lyx::support;
88 namespace Alert = frontend::Alert;
92 /// Return an inset of this class if it exists at the current cursor position
94 T * getInsetByCode(Cursor const & cur, InsetCode code)
97 Inset * inset = it.nextInset();
98 if (inset && inset->lyxCode() == code)
99 return static_cast<T*>(inset);
104 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
107 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
108 docstring const & contents)
110 DocIterator tmpdit = dit;
113 Inset const * inset = tmpdit.nextInset();
115 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
116 && (contents.empty() ||
117 static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
121 tmpdit.forwardInset();
128 /// Looks for next inset with one of the given codes.
129 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
133 DocIterator tmpdit = dit;
134 tmpdit.forwardInset();
139 Inset const * inset = tmpdit.nextInset();
141 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
142 contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
146 if (!findNextInset(tmpdit, codes, contents)) {
147 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
148 tmpdit = doc_iterator_begin(tmpdit.bottom().inset());
149 if (!findNextInset(tmpdit, codes, contents))
160 /// Looks for next inset with the given code
161 void findInset(DocIterator & dit, InsetCode code, bool same_content)
163 findInset(dit, vector<InsetCode>(1, code), same_content);
167 /// Moves cursor to the next inset with one of the given codes.
168 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
171 Cursor tmpcur = bv->cursor();
172 if (!findInset(tmpcur, codes, same_content)) {
173 bv->cursor().message(_("No more insets"));
177 tmpcur.clearSelection();
178 bv->setCursor(tmpcur);
183 /// Moves cursor to the next inset with given code.
184 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
186 gotoInset(bv, vector<InsetCode>(1, code), same_content);
190 /// A map from a Text to the associated text metrics
191 typedef map<Text const *, TextMetrics> TextMetricsCache;
193 enum ScreenUpdateStrategy {
203 /////////////////////////////////////////////////////////////////////
207 /////////////////////////////////////////////////////////////////////
209 struct BufferView::Private
211 Private(BufferView & bv): wh_(0), cursor_(bv),
212 anchor_pit_(0), anchor_ypos_(0),
213 last_inset_(0), gui_(0)
217 ScrollbarParameters scrollbarParameters_;
219 ScreenUpdateStrategy update_strategy_;
221 CoordCache coord_cache_;
223 /// Estimated average par height for scrollbar.
225 /// this is used to handle XSelection events in the right manner.
234 pit_type anchor_pit_;
238 vector<int> par_height_;
240 /// keyboard mapping object.
243 /// last visited inset.
244 /** kept to send setMouseHover(false).
245 * Not owned, so don't delete.
249 mutable TextMetricsCache text_metrics_;
252 /** Not owned, so don't delete.
254 frontend::GuiBufferViewDelegate * gui_;
258 BufferView::BufferView(Buffer & buf)
259 : width_(0), height_(0), buffer_(buf), d(new Private(*this))
261 d->xsel_cache_.set = false;
262 d->intl_.initKeyMapper(lyxrc.use_kbmap);
264 d->cursor_.push(buffer_.inset());
265 d->cursor_.resetAnchor();
266 d->cursor_.setCurrentFont();
268 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
269 graphics::Previews::get().generateBufferPreviews(buffer_);
273 BufferView::~BufferView()
275 // current buffer is going to be switched-off, save cursor pos
276 // Ideally, the whole cursor stack should be saved, but session
277 // currently can only handle bottom (whole document) level pit and pos.
278 // That is to say, if a cursor is in a nested inset, it will be
279 // restore to the left of the top level inset.
280 LastFilePosSection::FilePos fp;
281 fp.pit = d->cursor_.bottom().pit();
282 fp.pos = d->cursor_.bottom().pos();
283 LyX::ref().session().lastFilePos().save(buffer_.fileName(), fp);
289 Intl & BufferView::getIntl()
295 Intl const & BufferView::getIntl() const
301 CoordCache & BufferView::coordCache()
303 return d->coord_cache_;
307 CoordCache const & BufferView::coordCache() const
309 return d->coord_cache_;
313 Buffer & BufferView::buffer()
319 Buffer const & BufferView::buffer() const
325 bool BufferView::fitCursor()
327 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
328 frontend::FontMetrics const & fm =
329 theFontMetrics(d->cursor_.getFont().fontInfo());
330 int const asc = fm.maxAscent();
331 int const des = fm.maxDescent();
332 Point const p = getPos(d->cursor_, d->cursor_.boundary());
333 if (p.y_ - asc >= 0 && p.y_ + des < height_)
340 void BufferView::processUpdateFlags(Update::flags flags)
342 // last_inset_ points to the last visited inset. This pointer may become
343 // invalid because of keyboard editing. Since all such operations
344 // causes screen update(), I reset last_inset_ to avoid such a problem.
346 // This is close to a hot-path.
347 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
348 << "[fitcursor = " << (flags & Update::FitCursor)
349 << ", forceupdate = " << (flags & Update::Force)
350 << ", singlepar = " << (flags & Update::SinglePar)
351 << "] buffer: " << &buffer_);
353 buffer_.updateMacros();
355 // Now do the first drawing step if needed. This consists on updating
356 // the CoordCache in updateMetrics().
357 // The second drawing step is done in WorkArea::redraw() if needed.
359 // Case when no explicit update is requested.
361 // no need to redraw anything.
362 d->update_strategy_ = NoScreenUpdate;
366 if (flags == Update::Decoration) {
367 d->update_strategy_ = DecorationUpdate;
372 if (flags == Update::FitCursor
373 || flags == (Update::Decoration | Update::FitCursor)) {
374 // tell the frontend to update the screen if needed.
379 if (flags & Update::Decoration) {
380 d->update_strategy_ = DecorationUpdate;
384 // no screen update is needed.
385 d->update_strategy_ = NoScreenUpdate;
389 bool const full_metrics = flags & Update::Force || !singleParUpdate();
392 // We have to update the full screen metrics.
395 if (!(flags & Update::FitCursor)) {
396 // Nothing to do anymore. Trigger a redraw and return
401 // updateMetrics() does not update paragraph position
402 // This is done at draw() time. So we need a redraw!
406 // The cursor is off screen so ensure it is visible.
413 void BufferView::updateScrollbar()
418 Text & t = buffer_.text();
419 TextMetrics & tm = d->text_metrics_[&t];
421 LYXERR(Debug::GUI, " Updating scrollbar: height: "
422 << t.paragraphs().size()
423 << " curr par: " << d->cursor_.bottom().pit()
424 << " default height " << defaultRowHeight());
426 int const parsize = int(t.paragraphs().size());
427 if (d->par_height_.size() != parsize) {
428 d->par_height_.clear();
429 // FIXME: We assume a default paragraph height of 2 rows. This
430 // should probably be pondered with the screen width.
431 d->par_height_.resize(parsize, defaultRowHeight() * 2);
434 // It would be better to fix the scrollbar to understand
435 // values in [0..1] and divide everything by wh
437 // Look at paragraph heights on-screen
438 pit_type first_visible_pit = -1;
439 pair<pit_type, ParagraphMetrics const *> first = tm.first();
440 pair<pit_type, ParagraphMetrics const *> last = tm.last();
441 for (pit_type pit = first.first; pit <= last.first; ++pit) {
442 ParagraphMetrics const & pm = tm.parMetrics(pit);
443 d->par_height_[pit] = pm.height();
444 if (first_visible_pit >= 0 || pm.position() + pm.descent() <= 0)
446 first_visible_pit = pit;
447 LYXERR(Debug::SCROLLING, "first visible pit " << first_visible_pit);
448 // FIXME: we should look for the first visible row within
449 // the deepest inset!
450 int row_pos = pm.position();
451 size_t const nrows = pm.rows().size();
452 for (size_t i = 0; i != nrows; ++i) {
453 Row const & row = pm.rows()[i];
455 LYXERR(Debug::SCROLLING, "first visible row " << i
456 << "(row pos = " << row_pos << ");");
459 row_pos += row.height();
461 d->scrollbarParameters_.position = row_pos;
464 d->scrollbarParameters_.height = 0;
465 for (size_t i = 0; i != d->par_height_.size(); ++i) {
466 if (i == first_visible_pit)
467 d->scrollbarParameters_.position += d->scrollbarParameters_.height;
468 d->scrollbarParameters_.height += d->par_height_[i];
471 // We prefer fixed size line scrolling.
472 d->scrollbarParameters_.lineScrollHeight = defaultRowHeight();
476 ScrollbarParameters const & BufferView::scrollbarParameters() const
478 return d->scrollbarParameters_;
482 docstring BufferView::toolTip(int x, int y) const
484 // Get inset under mouse, if there is one.
485 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
487 // No inset, no tooltip...
489 return covering_inset->toolTip(*this, x, y);
493 void BufferView::scrollDocView(int value)
495 int const offset = value - d->scrollbarParameters_.position;
496 // If the offset is less than 2 screen height, prefer to scroll instead.
497 if (abs(offset) <= 2 * height_) {
503 for (size_t i = 0; i != d->par_height_.size(); ++i) {
504 par_pos += d->par_height_[i];
505 if (par_pos >= value) {
506 d->anchor_pit_ = pit_type(i);
511 LYXERR(Debug::SCROLLING, "value = " << value
512 << "\tanchor_ref_ = " << d->anchor_pit_
513 << "\tpar_pos = " << par_pos);
515 d->anchor_ypos_ = par_pos - value;
521 // FIXME: this method is not working well.
522 void BufferView::setCursorFromScrollbar()
524 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
526 int const height = 2 * defaultRowHeight();
527 int const first = height;
528 int const last = height_ - height;
529 Cursor & cur = d->cursor_;
531 switch (cursorStatus(cur)) {
533 // We reset the cursor because cursorStatus() does not
534 // work when the cursor is within mathed.
535 cur.reset(buffer_.inset());
536 tm.setCursorFromCoordinates(cur, 0, first);
537 cur.clearSelection();
540 // We reset the cursor because cursorStatus() does not
541 // work when the cursor is within mathed.
542 cur.reset(buffer_.inset());
543 tm.setCursorFromCoordinates(cur, 0, last);
544 cur.clearSelection();
547 int const y = getPos(cur, cur.boundary()).y_;
548 int const newy = min(last, max(y, first));
550 cur.reset(buffer_.inset());
551 tm.setCursorFromCoordinates(cur, 0, newy);
557 Change const BufferView::getCurrentChange() const
559 if (!d->cursor_.selection())
560 return Change(Change::UNCHANGED);
562 DocIterator dit = d->cursor_.selectionBegin();
563 return dit.paragraph().lookupChange(dit.pos());
567 // this could be used elsewhere as well?
568 // FIXME: This does not work within mathed!
569 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
571 Point const p = getPos(dit, dit.boundary());
574 if (p.y_ > workHeight())
580 void BufferView::saveBookmark(unsigned int idx)
582 // tenatively save bookmark, id and pos will be used to
583 // acturately locate a bookmark in a 'live' lyx session.
584 // pit and pos will be updated with bottom level pit/pos
586 LyX::ref().session().bookmarks().save(
588 d->cursor_.bottom().pit(),
589 d->cursor_.bottom().pos(),
590 d->cursor_.paragraph().id(),
595 // emit message signal.
596 message(_("Save bookmark"));
600 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
601 int top_id, pos_type top_pos)
603 bool success = false;
606 d->cursor_.clearSelection();
608 // if a valid par_id is given, try it first
609 // This is the case for a 'live' bookmark when unique paragraph ID
610 // is used to track bookmarks.
612 ParIterator par = buffer_.getParFromID(top_id);
613 if (par != buffer_.par_iterator_end()) {
614 doc_it = makeDocIterator(par, min(par->size(), top_pos));
615 // Some slices of the iterator may not be
616 // reachable (e.g. closed collapsable inset)
617 // so the dociterator may need to be
618 // shortened. Otherwise, setCursor may crash
619 // lyx when the cursor can not be set to these
621 size_t const n = doc_it.depth();
622 for (size_t i = 0; i < n; ++i)
623 if (doc_it[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
631 // if top_id == 0, or searching through top_id failed
632 // This is the case for a 'restored' bookmark when only bottom
633 // (document level) pit was saved. Because of this, bookmark
634 // restoration is inaccurate. If a bookmark was within an inset,
635 // it will be restored to the left of the outmost inset that contains
637 if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
638 doc_it = doc_iterator_begin(buffer_.inset());
639 doc_it.pit() = bottom_pit;
640 doc_it.pos() = min(bottom_pos, doc_it.paragraph().size());
645 // Note: only bottom (document) level pit is set.
647 // set the current font.
648 d->cursor_.setCurrentFont();
649 // To center the screen on this new position we need the
650 // paragraph position which is computed at draw() time.
651 // So we need a redraw!
661 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
663 if (lyxrc.rtl_support) {
664 if (d->cursor_.real_current_font.isRightToLeft()) {
665 if (d->intl_.keymap == Intl::PRIMARY)
666 d->intl_.keyMapSec();
668 if (d->intl_.keymap == Intl::SECONDARY)
669 d->intl_.keyMapPrim();
673 d->intl_.getTransManager().translateAndInsert(c, t, cur);
677 int BufferView::workWidth() const
683 void BufferView::showCursor()
685 // We are not properly started yet, delay until resizing is
690 LYXERR(Debug::SCROLLING, "recentering!");
692 CursorSlice & bot = d->cursor_.bottom();
693 TextMetrics & tm = d->text_metrics_[bot.text()];
695 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
696 int bot_pit = d->cursor_.bottom().pit();
697 if (bot_pit > max_pit) {
698 // FIXME: Why does this happen?
699 LYXERR0("bottom pit is greater that max pit: "
700 << bot_pit << " > " << max_pit);
704 if (bot_pit == tm.first().first - 1)
705 tm.newParMetricsUp();
706 else if (bot_pit == tm.last().first + 1)
707 tm.newParMetricsDown();
709 if (tm.has(bot_pit)) {
710 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
711 int offset = coordOffset(d->cursor_, d->cursor_.boundary()).y_;
712 int ypos = pm.position() + offset;
713 Dimension const & row_dim = d->cursor_.textRow().dimension();
714 if (ypos - row_dim.ascent() < 0)
715 scrollUp(- ypos + row_dim.ascent());
716 else if (ypos + row_dim.descent() > height_)
717 scrollDown(ypos - height_ + row_dim.descent());
718 // else, nothing to do, the cursor is already visible so we just return.
722 tm.redoParagraph(bot_pit);
723 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
724 int offset = coordOffset(d->cursor_, d->cursor_.boundary()).y_;
726 d->anchor_pit_ = bot_pit;
727 Dimension const & row_dim = d->cursor_.textRow().dimension();
729 if (d->anchor_pit_ == 0)
730 d->anchor_ypos_ = offset + pm.ascent();
731 else if (d->anchor_pit_ == max_pit)
732 d->anchor_ypos_ = height_ - offset - row_dim.descent();
734 d->anchor_ypos_ = offset + pm.ascent() - height_ / 2;
741 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
745 Cursor & cur = d->cursor_;
747 switch (cmd.action) {
750 flag.enabled(buffer_.undo().hasUndoStack());
753 flag.enabled(buffer_.undo().hasRedoStack());
755 case LFUN_FILE_INSERT:
756 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
757 case LFUN_FILE_INSERT_PLAINTEXT:
758 case LFUN_BOOKMARK_SAVE:
759 // FIXME: Actually, these LFUNS should be moved to Text
760 flag.enabled(cur.inTexted());
762 case LFUN_FONT_STATE:
763 case LFUN_LABEL_INSERT:
764 case LFUN_INFO_INSERT:
765 case LFUN_PARAGRAPH_GOTO:
767 case LFUN_REFERENCE_NEXT:
769 case LFUN_WORD_REPLACE:
772 case LFUN_MARK_TOGGLE:
773 case LFUN_SCREEN_RECENTER:
774 case LFUN_BIBTEX_DATABASE_ADD:
775 case LFUN_BIBTEX_DATABASE_DEL:
776 case LFUN_WORDS_COUNT:
777 case LFUN_NEXT_INSET_TOGGLE:
781 case LFUN_LABEL_GOTO: {
782 flag.enabled(!cmd.argument().empty()
783 || getInsetByCode<InsetRef>(cur, REF_CODE));
787 case LFUN_CHANGES_TRACK:
789 flag.setOnOff(buffer_.params().trackChanges);
792 case LFUN_CHANGES_OUTPUT:
794 flag.setOnOff(buffer_.params().outputChanges);
797 case LFUN_CHANGES_MERGE:
798 case LFUN_CHANGE_NEXT:
799 case LFUN_ALL_CHANGES_ACCEPT:
800 case LFUN_ALL_CHANGES_REJECT:
801 // TODO: context-sensitive enabling of LFUNs
802 // In principle, these command should only be enabled if there
803 // is a change in the document. However, without proper
804 // optimizations, this will inevitably result in poor performance.
808 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
809 flag.setOnOff(buffer_.params().compressed);
813 case LFUN_BUFFER_TOGGLE_EMBEDDING: {
814 flag.setOnOff(buffer_.params().embedded);
819 case LFUN_SCREEN_DOWN:
823 // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
824 // everywhere else before this can enabled:
825 case LFUN_SCREEN_UP_SELECT:
826 case LFUN_SCREEN_DOWN_SELECT:
830 case LFUN_LAYOUT_TABULAR:
831 flag.enabled(cur.innerInsetOfType(TABULAR_CODE));
835 case LFUN_LAYOUT_PARAGRAPH:
836 flag.enabled(cur.inset().forceDefaultParagraphs(cur.idx()));
839 case LFUN_INSET_SETTINGS: {
840 InsetCode code = cur.inset().lyxCode();
844 enable = cmd.argument() == "tabular";
847 enable = cmd.argument() == "ert";
850 enable = cmd.argument() == "float";
853 enable = cmd.argument() == "wrap";
856 enable = cmd.argument() == "note";
859 enable = cmd.argument() == "branch";
862 enable = cmd.argument() == "box";
865 enable = cmd.argument() == "listings";
870 flag.enabled(enable);
874 case LFUN_DIALOG_SHOW_NEW_INSET:
875 flag.enabled(cur.inset().lyxCode() != ERT_CODE &&
876 cur.inset().lyxCode() != LISTINGS_CODE);
877 if (cur.inset().lyxCode() == CAPTION_CODE) {
879 if (cur.inset().getStatus(cur, cmd, flag))
892 bool BufferView::dispatch(FuncRequest const & cmd)
894 //lyxerr << [ cmd = " << cmd << "]" << endl;
896 // Make sure that the cached BufferView is correct.
897 LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
898 << " arg[" << to_utf8(cmd.argument()) << ']'
899 << " x[" << cmd.x << ']'
900 << " y[" << cmd.y << ']'
901 << " button[" << cmd.button() << ']');
903 Cursor & cur = d->cursor_;
905 switch (cmd.action) {
908 cur.message(_("Undo"));
909 cur.clearSelection();
911 cur.message(_("No further undo information"));
915 cur.message(_("Redo"));
916 cur.clearSelection();
918 cur.message(_("No further redo information"));
921 case LFUN_FONT_STATE:
922 cur.message(cur.currentState());
925 case LFUN_BOOKMARK_SAVE:
926 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
929 case LFUN_LABEL_GOTO: {
930 docstring label = cmd.argument();
933 getInsetByCode<InsetRef>(d->cursor_,
936 label = inset->getParam("reference");
937 // persistent=false: use temp_bookmark
947 case LFUN_PARAGRAPH_GOTO: {
948 int const id = convert<int>(to_utf8(cmd.argument()));
950 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
951 b = theBufferList().next(b)) {
953 ParIterator par = b->getParFromID(id);
954 if (par == b->par_iterator_end()) {
955 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
957 LYXERR(Debug::INFO, "Paragraph " << par->id()
958 << " found in buffer `"
959 << b->absFileName() << "'.");
963 setCursor(makeDocIterator(par, 0));
966 // Switch to other buffer view and resend cmd
967 theLyXFunc().dispatch(FuncRequest(
968 LFUN_BUFFER_SWITCH, b->absFileName()));
969 theLyXFunc().dispatch(cmd);
979 gotoInset(this, NOTE_CODE, false);
982 case LFUN_REFERENCE_NEXT: {
983 vector<InsetCode> tmp;
984 tmp.push_back(LABEL_CODE);
985 tmp.push_back(REF_CODE);
986 gotoInset(this, tmp, true);
990 case LFUN_CHANGES_TRACK:
991 buffer_.params().trackChanges = !buffer_.params().trackChanges;
994 case LFUN_CHANGES_OUTPUT:
995 buffer_.params().outputChanges = !buffer_.params().outputChanges;
996 if (buffer_.params().outputChanges) {
997 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
998 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
999 LaTeXFeatures::isAvailable("xcolor");
1001 if (!dvipost && !xcolorsoul) {
1002 Alert::warning(_("Changes not shown in LaTeX output"),
1003 _("Changes will not be highlighted in LaTeX output, "
1004 "because neither dvipost nor xcolor/soul are installed.\n"
1005 "Please install these packages or redefine "
1006 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1007 } else if (!xcolorsoul) {
1008 Alert::warning(_("Changes not shown in LaTeX output"),
1009 _("Changes will not be highlighted in LaTeX output "
1010 "when using pdflatex, because xcolor and soul are not installed.\n"
1011 "Please install both packages or redefine "
1012 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1017 case LFUN_CHANGE_NEXT:
1018 findNextChange(this);
1021 case LFUN_CHANGES_MERGE:
1022 if (findNextChange(this))
1023 showDialog("changes");
1026 case LFUN_ALL_CHANGES_ACCEPT:
1027 // select complete document
1028 d->cursor_.reset(buffer_.inset());
1029 d->cursor_.selHandle(true);
1030 buffer_.text().cursorBottom(d->cursor_);
1031 // accept everything in a single step to support atomic undo
1032 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1035 case LFUN_ALL_CHANGES_REJECT:
1036 // select complete document
1037 d->cursor_.reset(buffer_.inset());
1038 d->cursor_.selHandle(true);
1039 buffer_.text().cursorBottom(d->cursor_);
1040 // reject everything in a single step to support atomic undo
1041 // Note: reject does not work recursively; the user may have to repeat the operation
1042 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1045 case LFUN_WORD_FIND:
1049 case LFUN_WORD_REPLACE: {
1050 bool has_deleted = false;
1051 if (cur.selection()) {
1052 DocIterator beg = cur.selectionBegin();
1053 DocIterator end = cur.selectionEnd();
1054 if (beg.pit() == end.pit()) {
1055 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1056 if (cur.paragraph().isDeleted(p))
1061 replace(this, cmd, has_deleted);
1066 cur.clearSelection();
1068 cur.message(from_utf8(N_("Mark off")));
1072 cur.clearSelection();
1075 cur.message(from_utf8(N_("Mark on")));
1078 case LFUN_MARK_TOGGLE:
1079 cur.clearSelection();
1082 cur.message(from_utf8(N_("Mark removed")));
1085 cur.message(from_utf8(N_("Mark set")));
1090 case LFUN_SCREEN_RECENTER:
1094 case LFUN_BIBTEX_DATABASE_ADD: {
1095 Cursor tmpcur = d->cursor_;
1096 findInset(tmpcur, BIBTEX_CODE, false);
1097 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1100 if (inset->addDatabase(to_utf8(cmd.argument())))
1101 buffer_.updateBibfilesCache();
1106 case LFUN_BIBTEX_DATABASE_DEL: {
1107 Cursor tmpcur = d->cursor_;
1108 findInset(tmpcur, BIBTEX_CODE, false);
1109 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1112 if (inset->delDatabase(to_utf8(cmd.argument())))
1113 buffer_.updateBibfilesCache();
1118 case LFUN_WORDS_COUNT: {
1119 DocIterator from, to;
1120 if (cur.selection()) {
1121 from = cur.selectionBegin();
1122 to = cur.selectionEnd();
1124 from = doc_iterator_begin(buffer_.inset());
1125 to = doc_iterator_end(buffer_.inset());
1127 int const count = countWords(from, to);
1130 if (cur.selection())
1131 message = bformat(_("%1$d words in selection."),
1134 message = bformat(_("%1$d words in document."),
1138 if (cur.selection())
1139 message = _("One word in selection.");
1141 message = _("One word in document.");
1144 Alert::information(_("Count words"), message);
1148 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1149 // turn compression on/off
1150 buffer_.params().compressed = !buffer_.params().compressed;
1153 case LFUN_BUFFER_TOGGLE_EMBEDDING:
1154 // turn embedding on/off
1155 buffer_.embeddedFiles().enable(!buffer_.params().embedded);
1158 case LFUN_NEXT_INSET_TOGGLE: {
1159 // this is the real function we want to invoke
1160 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1161 // if there is an inset at cursor, see whether it
1163 Inset * inset = cur.nextInset();
1165 if (inset->isActive()) {
1166 Cursor tmpcur = cur;
1167 tmpcur.pushBackward(*inset);
1168 inset->dispatch(tmpcur, tmpcmd);
1169 if (tmpcur.result().dispatched()) {
1172 } else if (inset->editable() == Inset::IS_EDITABLE) {
1173 inset->edit(cur, true);
1176 // if it did not work, try the underlying inset.
1177 if (!cur.result().dispatched())
1178 cur.dispatch(tmpcmd);
1180 if (cur.result().dispatched())
1181 cur.clearSelection();
1186 case LFUN_SCREEN_UP:
1187 case LFUN_SCREEN_DOWN: {
1188 Point p = getPos(cur, cur.boundary());
1189 if (p.y_ < 0 || p.y_ > height_) {
1190 // The cursor is off-screen so recenter before proceeding.
1192 p = getPos(cur, cur.boundary());
1194 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1195 cur.reset(buffer_.inset());
1196 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1197 //FIXME: what to do with cur.x_target()?
1202 case LFUN_SCREEN_UP_SELECT:
1203 case LFUN_SCREEN_DOWN_SELECT: {
1204 // Those two are not ready yet for consumption.
1207 cur.selHandle(true);
1208 size_t initial_depth = cur.depth();
1209 Point const p = getPos(cur, cur.boundary());
1210 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1211 // FIXME: We need to verify if the cursor stayed within an inset...
1212 //cur.reset(buffer_.inset());
1213 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1215 while (cur.depth() > initial_depth) {
1218 // FIXME: we need to do a redraw again because of the selection
1219 // But no screen update is needed.
1220 d->update_strategy_ = NoScreenUpdate;
1233 docstring const BufferView::requestSelection()
1235 Cursor & cur = d->cursor_;
1237 if (!cur.selection()) {
1238 d->xsel_cache_.set = false;
1242 if (!d->xsel_cache_.set ||
1243 cur.top() != d->xsel_cache_.cursor ||
1244 cur.anchor_.top() != d->xsel_cache_.anchor)
1246 d->xsel_cache_.cursor = cur.top();
1247 d->xsel_cache_.anchor = cur.anchor_.top();
1248 d->xsel_cache_.set = cur.selection();
1249 return cur.selectionAsString(false);
1255 void BufferView::clearSelection()
1257 d->cursor_.clearSelection();
1258 // Clear the selection buffer. Otherwise a subsequent
1259 // middle-mouse-button paste would use the selection buffer,
1260 // not the more current external selection.
1261 cap::clearSelection();
1262 d->xsel_cache_.set = false;
1263 // The buffer did not really change, but this causes the
1264 // redraw we need because we cleared the selection above.
1269 void BufferView::resize(int width, int height)
1271 // Update from work area
1275 // Clear the paragraph height cache.
1276 d->par_height_.clear();
1282 Inset const * BufferView::getCoveringInset(Text const & text,
1285 TextMetrics & tm = d->text_metrics_[&text];
1286 Inset * inset = tm.checkInsetHit(x, y);
1290 if (!inset->descendable())
1291 // No need to go further down if the inset is not
1295 size_t cell_number = inset->nargs();
1296 // Check all the inner cell.
1297 for (size_t i = 0; i != cell_number; ++i) {
1298 Text const * inner_text = inset->getText(i);
1301 Inset const * inset_deeper =
1302 getCoveringInset(*inner_text, x, y);
1304 return inset_deeper;
1312 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1314 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1316 // This is only called for mouse related events including
1317 // LFUN_FILE_OPEN generated by drag-and-drop.
1318 FuncRequest cmd = cmd0;
1321 cur.push(buffer_.inset());
1322 cur.selection() = d->cursor_.selection();
1324 // Either the inset under the cursor or the
1325 // surrounding Text will handle this event.
1327 // make sure we stay within the screen...
1328 cmd.y = min(max(cmd.y, -1), height_);
1330 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1332 // Get inset under mouse, if there is one.
1333 Inset const * covering_inset =
1334 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1335 if (covering_inset == d->last_inset_)
1336 // Same inset, no need to do anything...
1339 bool need_redraw = false;
1340 // const_cast because of setMouseHover().
1341 Inset * inset = const_cast<Inset *>(covering_inset);
1343 // Remove the hint on the last hovered inset (if any).
1344 need_redraw |= d->last_inset_->setMouseHover(false);
1346 // Highlighted the newly hovered inset (if any).
1347 need_redraw |= inset->setMouseHover(true);
1348 d->last_inset_ = inset;
1352 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1353 << cmd.x << ", " << cmd.y << ")");
1355 d->update_strategy_ = DecorationUpdate;
1357 // This event (moving without mouse click) is not passed further.
1358 // This should be changed if it is further utilized.
1363 // Build temporary cursor.
1364 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1366 // Put anchor at the same position.
1369 // Try to dispatch to an non-editable inset near this position
1370 // via the temp cursor. If the inset wishes to change the real
1371 // cursor it has to do so explicitly by using
1372 // cur.bv().cursor() = cur; (or similar)
1374 inset->dispatch(cur, cmd);
1376 // Now dispatch to the temporary cursor. If the real cursor should
1377 // be modified, the inset's dispatch has to do so explicitly.
1378 if (!cur.result().dispatched())
1381 //Do we have a selection?
1382 theSelection().haveSelection(cursor().selection());
1384 // If the command has been dispatched,
1385 if (cur.result().dispatched()
1386 // an update is asked,
1387 && cur.result().update())
1388 processUpdateFlags(cur.result().update());
1392 void BufferView::scroll(int y)
1401 void BufferView::scrollDown(int offset)
1403 Text * text = &buffer_.text();
1404 TextMetrics & tm = d->text_metrics_[text];
1405 int ymax = height_ + offset;
1407 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1408 int bottom_pos = last.second->position() + last.second->descent();
1409 if (last.first + 1 == int(text->paragraphs().size())) {
1410 if (bottom_pos <= height_)
1412 offset = min(offset, bottom_pos - height_);
1415 if (bottom_pos > ymax)
1417 tm.newParMetricsDown();
1419 d->anchor_ypos_ -= offset;
1425 void BufferView::scrollUp(int offset)
1427 Text * text = &buffer_.text();
1428 TextMetrics & tm = d->text_metrics_[text];
1429 int ymin = - offset;
1431 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1432 int top_pos = first.second->position() - first.second->ascent();
1433 if (first.first == 0) {
1436 offset = min(offset, - top_pos);
1441 tm.newParMetricsUp();
1443 d->anchor_ypos_ += offset;
1449 void BufferView::setCursorFromRow(int row)
1454 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1456 d->cursor_.reset(buffer_.inset());
1458 buffer_.text().setCursor(d->cursor_, 0, 0);
1460 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1464 void BufferView::gotoLabel(docstring const & label)
1466 for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1467 vector<docstring> labels;
1468 it->getLabelList(buffer_, labels);
1469 if (find(labels.begin(), labels.end(), label) != labels.end()) {
1478 TextMetrics const & BufferView::textMetrics(Text const * t) const
1480 return const_cast<BufferView *>(this)->textMetrics(t);
1484 TextMetrics & BufferView::textMetrics(Text const * t)
1486 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
1487 if (tmc_it == d->text_metrics_.end()) {
1488 tmc_it = d->text_metrics_.insert(
1489 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1491 return tmc_it->second;
1495 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1498 return textMetrics(t).parMetrics(pit);
1502 int BufferView::workHeight() const
1508 void BufferView::setCursor(DocIterator const & dit)
1510 size_t const n = dit.depth();
1511 for (size_t i = 0; i < n; ++i)
1512 dit[i].inset().edit(d->cursor_, true);
1514 d->cursor_.setCursor(dit);
1515 d->cursor_.selection() = false;
1519 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1521 // Would be wrong to delete anything if we have a selection.
1522 if (cur.selection())
1525 bool need_anchor_change = false;
1526 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1527 need_anchor_change);
1529 if (need_anchor_change)
1535 updateLabels(buffer_);
1543 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1545 BOOST_ASSERT(&cur.bv() == this);
1548 // this event will clear selection so we save selection for
1549 // persistent selection
1550 cap::saveSelection(cursor());
1552 // Has the cursor just left the inset?
1553 bool badcursor = false;
1554 bool leftinset = (&d->cursor_.inset() != &cur.inset());
1556 badcursor = notifyCursorLeaves(d->cursor_, cur);
1558 // FIXME: shift-mouse selection doesn't work well across insets.
1559 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1561 // do the dEPM magic if needed
1562 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1563 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1564 // the leftinset bool would not be necessary (badcursor instead).
1565 bool update = leftinset;
1566 if (!do_selection && !badcursor && d->cursor_.inTexted())
1567 update |= checkDepm(cur, d->cursor_);
1569 // if the cursor was in an empty script inset and the new
1570 // position is in the nucleus of the inset, notifyCursorLeaves
1571 // will kill the script inset itself. So we check all the
1572 // elements of the cursor to make sure that they are correct.
1573 // For an example, see bug 2933:
1574 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1575 // The code below could maybe be moved to a DocIterator method.
1576 //lyxerr << "cur before " << cur <<endl;
1577 DocIterator dit(cur.inset());
1578 dit.push_back(cur.bottom());
1580 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1581 dit.push_back(cur[i]);
1584 //lyxerr << "5 cur after" << dit <<endl;
1586 d->cursor_.setCursor(dit);
1587 d->cursor_.boundary(cur.boundary());
1589 d->cursor_.setSelection();
1591 d->cursor_.clearSelection();
1593 d->cursor_.finishUndo();
1594 d->cursor_.setCurrentFont();
1599 void BufferView::putSelectionAt(DocIterator const & cur,
1600 int length, bool backwards)
1602 d->cursor_.clearSelection();
1608 d->cursor_.pos() += length;
1609 d->cursor_.setSelection(d->cursor_, -length);
1611 d->cursor_.setSelection(d->cursor_, length);
1616 Cursor & BufferView::cursor()
1622 Cursor const & BufferView::cursor() const
1628 pit_type BufferView::anchor_ref() const
1630 return d->anchor_pit_;
1634 bool BufferView::singleParUpdate()
1636 Text & buftext = buffer_.text();
1637 pit_type const bottom_pit = d->cursor_.bottom().pit();
1638 TextMetrics & tm = textMetrics(&buftext);
1639 int old_height = tm.parMetrics(bottom_pit).height();
1641 // In Single Paragraph mode, rebreak only
1642 // the (main text, not inset!) paragraph containing the cursor.
1643 // (if this paragraph contains insets etc., rebreaking will
1644 // recursively descend)
1645 tm.redoParagraph(bottom_pit);
1646 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
1647 if (pm.height() != old_height)
1648 // Paragraph height has changed so we cannot proceed to
1649 // the singlePar optimisation.
1652 d->update_strategy_ = SingleParUpdate;
1654 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
1655 << " y2: " << pm.position() + pm.descent()
1656 << " pit: " << bottom_pit
1657 << " singlepar: 1");
1662 void BufferView::updateMetrics()
1664 Text & buftext = buffer_.text();
1665 pit_type const npit = int(buftext.paragraphs().size());
1667 // Clear out the position cache in case of full screen redraw,
1668 d->coord_cache_.clear();
1670 // Clear out paragraph metrics to avoid having invalid metrics
1671 // in the cache from paragraphs not relayouted below
1672 // The complete text metrics will be redone.
1673 d->text_metrics_.clear();
1675 TextMetrics & tm = textMetrics(&buftext);
1677 // Rebreak anchor paragraph.
1678 tm.redoParagraph(d->anchor_pit_);
1679 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
1680 anchor_pm.setPosition(d->anchor_ypos_);
1682 LYXERR(Debug::PAINTING, "metrics: "
1683 << " anchor pit = " << d->anchor_pit_
1684 << " anchor ypos = " << d->anchor_ypos_);
1686 // Redo paragraphs above anchor if necessary.
1687 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
1688 // We are now just above the anchor paragraph.
1689 pit_type pit1 = d->anchor_pit_ - 1;
1690 for (; pit1 >= 0 && y1 >= 0; --pit1) {
1691 tm.redoParagraph(pit1);
1692 ParagraphMetrics & pm = tm.par_metrics_[pit1];
1694 // Save the paragraph position in the cache.
1699 // Redo paragraphs below the anchor if necessary.
1700 int y2 = d->anchor_ypos_ + anchor_pm.descent();
1701 // We are now just below the anchor paragraph.
1702 pit_type pit2 = d->anchor_pit_ + 1;
1703 for (; pit2 < npit && y2 <= height_; ++pit2) {
1704 tm.redoParagraph(pit2);
1705 ParagraphMetrics & pm = tm.par_metrics_[pit2];
1707 // Save the paragraph position in the cache.
1712 LYXERR(Debug::PAINTING, "Metrics: "
1713 << " anchor pit = " << d->anchor_pit_
1714 << " anchor ypos = " << d->anchor_ypos_
1717 << " pit1 = " << pit1
1718 << " pit2 = " << pit2);
1720 d->update_strategy_ = FullScreenUpdate;
1722 if (lyxerr.debugging(Debug::WORKAREA)) {
1723 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
1724 d->coord_cache_.dump();
1729 void BufferView::insertLyXFile(FileName const & fname)
1731 BOOST_ASSERT(d->cursor_.inTexted());
1733 // Get absolute path of file and add ".lyx"
1734 // to the filename if necessary
1735 FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
1737 docstring const disp_fn = makeDisplayPath(filename.absFilename());
1738 // emit message signal.
1739 message(bformat(_("Inserting document %1$s..."), disp_fn));
1742 Buffer buf("", false);
1743 if (buf.loadLyXFile(filename)) {
1744 ErrorList & el = buffer_.errorList("Parse");
1745 // Copy the inserted document error list into the current buffer one.
1746 el = buf.errorList("Parse");
1747 buffer_.undo().recordUndo(d->cursor_);
1748 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
1749 buf.params().getTextClassPtr(), el);
1750 res = _("Document %1$s inserted.");
1752 res = _("Could not insert document %1$s");
1757 // emit message signal.
1758 message(bformat(res, disp_fn));
1759 buffer_.errors("Parse");
1763 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1769 // Addup contribution of nested insets, from inside to outside,
1770 // keeping the outer paragraph for a special handling below
1771 for (size_t i = dit.depth() - 1; i >= 1; --i) {
1772 CursorSlice const & sl = dit[i];
1776 // get relative position inside sl.inset()
1777 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
1779 // Make relative position inside of the edited inset relative to sl.inset()
1783 // In case of an RTL inset, the edited inset will be positioned to the left
1786 bool boundary_i = boundary && i + 1 == dit.depth();
1787 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
1792 // remember width for the case that sl.inset() is positioned in an RTL inset
1793 if (i && dit[i - 1].text()) {
1794 // If this Inset is inside a Text Inset, retrieve the Dimension
1795 // from the containing text instead of using Inset::dimension() which
1796 // might not be implemented.
1797 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
1798 // elimination of Inset::dim_ cache. This coordOffset() method needs
1799 // to be rewritten in light of the new design.
1800 Dimension const & dim = parMetrics(dit[i - 1].text(),
1801 dit[i - 1].pit()).insetDimension(&sl.inset());
1804 Dimension const dim = sl.inset().dimension(*this);
1808 //lyxerr << "Cursor::getPos, i: "
1809 // << i << " x: " << xx << " y: " << y << endl;
1812 // Add contribution of initial rows of outermost paragraph
1813 CursorSlice const & sl = dit[0];
1814 TextMetrics const & tm = textMetrics(sl.text());
1815 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
1816 BOOST_ASSERT(!pm.rows().empty());
1817 y -= pm.rows()[0].ascent();
1819 // FIXME: document this mess
1821 if (sl.pos() > 0 && dit.depth() == 1) {
1823 if (pos && boundary)
1825 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
1826 rend = pm.pos2row(pos);
1828 rend = pm.pos2row(sl.pos());
1830 size_t rend = pm.pos2row(sl.pos());
1832 for (size_t rit = 0; rit != rend; ++rit)
1833 y += pm.rows()[rit].height();
1834 y += pm.rows()[rend].ascent();
1836 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
1838 // Make relative position from the nested inset now bufferview absolute.
1839 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
1842 // In the RTL case place the nested inset at the left of the cursor in
1843 // the outer paragraph
1844 bool boundary_1 = boundary && 1 == dit.depth();
1845 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
1853 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
1855 CursorSlice const & bot = dit.bottom();
1856 TextMetrics const & tm = textMetrics(bot.text());
1857 if (!tm.has(bot.pit()))
1858 return Point(-1, -1);
1860 Point p = coordOffset(dit, boundary); // offset from outer paragraph
1861 p.y_ += tm.parMetrics(bot.pit()).position();
1866 void BufferView::draw(frontend::Painter & pain)
1868 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
1869 Text & text = buffer_.text();
1870 TextMetrics const & tm = d->text_metrics_[&text];
1871 int const y = tm.first().second->position();
1872 PainterInfo pi(this, pain);
1874 switch (d->update_strategy_) {
1876 case NoScreenUpdate:
1877 // If no screen painting is actually needed, only some the different
1878 // coordinates of insets and paragraphs needs to be updated.
1879 pi.full_repaint = true;
1880 pi.pain.setDrawingEnabled(false);
1884 case SingleParUpdate:
1885 pi.full_repaint = false;
1886 // In general, only the current row of the outermost paragraph
1887 // will be redrawn. Particular cases where selection spans
1888 // multiple paragraph are correctly detected in TextMetrics.
1892 case DecorationUpdate:
1893 // FIXME: We should also distinguish DecorationUpdate to avoid text
1894 // drawing if possible. This is not possible to do easily right now
1895 // because of the single backing pixmap.
1897 case FullScreenUpdate:
1898 // The whole screen, including insets, will be refreshed.
1899 pi.full_repaint = true;
1901 // Clear background.
1902 pain.fillRectangle(0, 0, width_, height_,
1903 buffer_.inset().backgroundColor());
1908 // and possibly grey out below
1909 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1910 int const y2 = lastpm.second->position() + lastpm.second->descent();
1912 pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
1915 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
1917 // The scrollbar needs an update.
1920 // Normalize anchor for next time
1921 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
1922 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1923 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
1924 ParagraphMetrics const & pm = tm.parMetrics(pit);
1925 if (pm.position() + pm.descent() > 0) {
1926 d->anchor_pit_ = pit;
1927 d->anchor_ypos_ = pm.position();
1931 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
1932 << " anchor ypos = " << d->anchor_ypos_);
1936 void BufferView::message(docstring const & msg)
1939 d->gui_->message(msg);
1943 void BufferView::showDialog(string const & name)
1946 d->gui_->showDialog(name, string());
1950 void BufferView::showDialog(string const & name,
1951 string const & data, Inset * inset)
1954 d->gui_->showDialog(name, data, inset);
1958 void BufferView::updateDialog(string const & name, string const & data)
1961 d->gui_->updateDialog(name, data);
1965 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
1971 // FIXME: Move this out of BufferView again
1972 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
1974 if (!fname.isReadableFile()) {
1975 docstring const error = from_ascii(strerror(errno));
1976 docstring const file = makeDisplayPath(fname.absFilename(), 50);
1977 docstring const text =
1978 bformat(_("Could not read the specified document\n"
1979 "%1$s\ndue to the error: %2$s"), file, error);
1980 Alert::error(_("Could not read file"), text);
1984 if (!fname.isReadableFile()) {
1985 docstring const file = makeDisplayPath(fname.absFilename(), 50);
1986 docstring const text =
1987 bformat(_("%1$s\n is not readable."), file);
1988 Alert::error(_("Could not open file"), text);
1992 // FIXME UNICODE: We don't know the encoding of the file
1993 docstring file_content = fname.fileContents("UTF-8");
1994 if (file_content.empty()) {
1995 Alert::error(_("Reading not UTF-8 encoded file"),
1996 _("The file is not UTF-8 encoded.\n"
1997 "It will be read as local 8Bit-encoded.\n"
1998 "If this does not give the correct result\n"
1999 "then please change the encoding of the file\n"
2000 "to UTF-8 with a program other than LyX.\n"));
2001 file_content = fname.fileContents("local8bit");
2004 return normalize_c(file_content);
2008 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2010 docstring const tmpstr = contentsOfPlaintextFile(f);
2015 Cursor & cur = cursor();
2016 cap::replaceSelection(cur);
2017 buffer_.undo().recordUndo(cur);
2019 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2021 cur.innerText()->insertStringAsLines(cur, tmpstr);