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);
182 /// Moves cursor to the next inset with given code.
183 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
185 gotoInset(bv, vector<InsetCode>(1, code), same_content);
189 /// A map from a Text to the associated text metrics
190 typedef map<Text const *, TextMetrics> TextMetricsCache;
192 enum ScreenUpdateStrategy {
202 /////////////////////////////////////////////////////////////////////
206 /////////////////////////////////////////////////////////////////////
208 struct BufferView::Private
210 Private(BufferView & bv): wh_(0), cursor_(bv),
211 anchor_pit_(0), anchor_ypos_(0),
212 last_inset_(0), gui_(0)
216 ScrollbarParameters scrollbarParameters_;
218 ScreenUpdateStrategy update_strategy_;
220 CoordCache coord_cache_;
222 /// Estimated average par height for scrollbar.
224 /// this is used to handle XSelection events in the right manner.
233 pit_type anchor_pit_;
237 vector<int> par_height_;
239 /// keyboard mapping object.
242 /// last visited inset.
243 /** kept to send setMouseHover(false).
244 * Not owned, so don't delete.
248 mutable TextMetricsCache text_metrics_;
251 /** Not owned, so don't delete.
253 frontend::GuiBufferViewDelegate * gui_;
257 BufferView::BufferView(Buffer & buf)
258 : width_(0), height_(0), buffer_(buf), d(new Private(*this))
260 d->xsel_cache_.set = false;
261 d->intl_.initKeyMapper(lyxrc.use_kbmap);
263 d->cursor_.push(buffer_.inset());
264 d->cursor_.resetAnchor();
265 d->cursor_.setCurrentFont();
267 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
268 graphics::Previews::get().generateBufferPreviews(buffer_);
272 BufferView::~BufferView()
274 // current buffer is going to be switched-off, save cursor pos
275 // Ideally, the whole cursor stack should be saved, but session
276 // currently can only handle bottom (whole document) level pit and pos.
277 // That is to say, if a cursor is in a nested inset, it will be
278 // restore to the left of the top level inset.
279 LastFilePosSection::FilePos fp;
280 fp.pit = d->cursor_.bottom().pit();
281 fp.pos = d->cursor_.bottom().pos();
282 LyX::ref().session().lastFilePos().save(buffer_.fileName(), fp);
288 Intl & BufferView::getIntl()
294 Intl const & BufferView::getIntl() const
300 CoordCache & BufferView::coordCache()
302 return d->coord_cache_;
306 CoordCache const & BufferView::coordCache() const
308 return d->coord_cache_;
312 Buffer & BufferView::buffer()
318 Buffer const & BufferView::buffer() const
324 bool BufferView::fitCursor()
326 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
327 frontend::FontMetrics const & fm =
328 theFontMetrics(d->cursor_.getFont().fontInfo());
329 int const asc = fm.maxAscent();
330 int const des = fm.maxDescent();
331 Point const p = getPos(d->cursor_, d->cursor_.boundary());
332 if (p.y_ - asc >= 0 && p.y_ + des < height_)
339 void BufferView::processUpdateFlags(Update::flags flags)
341 // last_inset_ points to the last visited inset. This pointer may become
342 // invalid because of keyboard editing. Since all such operations
343 // causes screen update(), I reset last_inset_ to avoid such a problem.
345 // This is close to a hot-path.
346 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
347 << "[fitcursor = " << (flags & Update::FitCursor)
348 << ", forceupdate = " << (flags & Update::Force)
349 << ", singlepar = " << (flags & Update::SinglePar)
350 << "] buffer: " << &buffer_);
352 buffer_.updateMacros();
354 // Now do the first drawing step if needed. This consists on updating
355 // the CoordCache in updateMetrics().
356 // The second drawing step is done in WorkArea::redraw() if needed.
358 // Case when no explicit update is requested.
360 // no need to redraw anything.
361 d->update_strategy_ = NoScreenUpdate;
365 if (flags == Update::Decoration) {
366 d->update_strategy_ = DecorationUpdate;
371 if (flags == Update::FitCursor
372 || flags == (Update::Decoration | Update::FitCursor)) {
373 // tell the frontend to update the screen if needed.
378 if (flags & Update::Decoration) {
379 d->update_strategy_ = DecorationUpdate;
383 // no screen update is needed.
384 d->update_strategy_ = NoScreenUpdate;
388 bool const full_metrics = flags & Update::Force || !singleParUpdate();
391 // We have to update the full screen metrics.
394 if (!(flags & Update::FitCursor)) {
395 // Nothing to do anymore. Trigger a redraw and return
400 // updateMetrics() does not update paragraph position
401 // This is done at draw() time. So we need a redraw!
405 // The cursor is off screen so ensure it is visible.
412 void BufferView::updateScrollbar()
417 Text & t = buffer_.text();
418 TextMetrics & tm = d->text_metrics_[&t];
420 LYXERR(Debug::GUI, " Updating scrollbar: height: "
421 << t.paragraphs().size()
422 << " curr par: " << d->cursor_.bottom().pit()
423 << " default height " << defaultRowHeight());
425 int const parsize = int(t.paragraphs().size());
426 if (d->par_height_.size() != parsize) {
427 d->par_height_.clear();
428 // FIXME: We assume a default paragraph height of 2 rows. This
429 // should probably be pondered with the screen width.
430 d->par_height_.resize(parsize, defaultRowHeight() * 2);
433 // It would be better to fix the scrollbar to understand
434 // values in [0..1] and divide everything by wh
436 // Look at paragraph heights on-screen
437 pit_type first_visible_pit = -1;
438 pair<pit_type, ParagraphMetrics const *> first = tm.first();
439 pair<pit_type, ParagraphMetrics const *> last = tm.last();
440 for (pit_type pit = first.first; pit <= last.first; ++pit) {
441 ParagraphMetrics const & pm = tm.parMetrics(pit);
442 d->par_height_[pit] = pm.height();
443 if (first_visible_pit >= 0 || pm.position() + pm.descent() <= 0)
445 first_visible_pit = pit;
446 LYXERR(Debug::SCROLLING, "first visible pit " << first_visible_pit);
447 // FIXME: we should look for the first visible row within
448 // the deepest inset!
449 int row_pos = pm.position();
450 size_t const nrows = pm.rows().size();
451 for (size_t i = 0; i != nrows; ++i) {
452 Row const & row = pm.rows()[i];
454 LYXERR(Debug::SCROLLING, "first visible row " << i
455 << "(row pos = " << row_pos << ");");
458 row_pos += row.height();
460 d->scrollbarParameters_.position = row_pos;
463 d->scrollbarParameters_.height = 0;
464 for (size_t i = 0; i != d->par_height_.size(); ++i) {
465 if (i == first_visible_pit)
466 d->scrollbarParameters_.position += d->scrollbarParameters_.height;
467 d->scrollbarParameters_.height += d->par_height_[i];
470 // We prefer fixed size line scrolling.
471 d->scrollbarParameters_.lineScrollHeight = defaultRowHeight();
475 ScrollbarParameters const & BufferView::scrollbarParameters() const
477 return d->scrollbarParameters_;
481 void BufferView::scrollDocView(int value)
483 int const offset = value - d->scrollbarParameters_.position;
484 // If the offset is less than 2 screen height, prefer to scroll instead.
485 if (abs(offset) <= 2 * height_) {
491 for (size_t i = 0; i != d->par_height_.size(); ++i) {
492 par_pos += d->par_height_[i];
493 if (par_pos >= value) {
494 d->anchor_pit_ = pit_type(i);
499 LYXERR(Debug::SCROLLING, "value = " << value
500 << "\tanchor_ref_ = " << d->anchor_pit_
501 << "\tpar_pos = " << par_pos);
503 d->anchor_ypos_ = par_pos - value;
509 // FIXME: this method is not working well.
510 void BufferView::setCursorFromScrollbar()
512 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
514 int const height = 2 * defaultRowHeight();
515 int const first = height;
516 int const last = height_ - height;
517 Cursor & cur = d->cursor_;
519 switch (cursorStatus(cur)) {
521 // We reset the cursor because cursorStatus() does not
522 // work when the cursor is within mathed.
523 cur.reset(buffer_.inset());
524 tm.setCursorFromCoordinates(cur, 0, first);
525 cur.clearSelection();
528 // We reset the cursor because cursorStatus() does not
529 // work when the cursor is within mathed.
530 cur.reset(buffer_.inset());
531 tm.setCursorFromCoordinates(cur, 0, last);
532 cur.clearSelection();
535 int const y = getPos(cur, cur.boundary()).y_;
536 int const newy = min(last, max(y, first));
538 cur.reset(buffer_.inset());
539 tm.setCursorFromCoordinates(cur, 0, newy);
545 Change const BufferView::getCurrentChange() const
547 if (!d->cursor_.selection())
548 return Change(Change::UNCHANGED);
550 DocIterator dit = d->cursor_.selectionBegin();
551 return dit.paragraph().lookupChange(dit.pos());
555 // this could be used elsewhere as well?
556 // FIXME: This does not work within mathed!
557 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
559 Point const p = getPos(dit, dit.boundary());
562 if (p.y_ > workHeight())
568 void BufferView::saveBookmark(unsigned int idx)
570 // tenatively save bookmark, id and pos will be used to
571 // acturately locate a bookmark in a 'live' lyx session.
572 // pit and pos will be updated with bottom level pit/pos
574 LyX::ref().session().bookmarks().save(
576 d->cursor_.bottom().pit(),
577 d->cursor_.bottom().pos(),
578 d->cursor_.paragraph().id(),
583 // emit message signal.
584 message(_("Save bookmark"));
588 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
589 int top_id, pos_type top_pos)
591 bool success = false;
594 d->cursor_.clearSelection();
596 // if a valid par_id is given, try it first
597 // This is the case for a 'live' bookmark when unique paragraph ID
598 // is used to track bookmarks.
600 ParIterator par = buffer_.getParFromID(top_id);
601 if (par != buffer_.par_iterator_end()) {
602 doc_it = makeDocIterator(par, min(par->size(), top_pos));
603 // Some slices of the iterator may not be
604 // reachable (e.g. closed collapsable inset)
605 // so the dociterator may need to be
606 // shortened. Otherwise, setCursor may crash
607 // lyx when the cursor can not be set to these
609 size_t const n = doc_it.depth();
610 for (size_t i = 0; i < n; ++i)
611 if (doc_it[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
619 // if top_id == 0, or searching through top_id failed
620 // This is the case for a 'restored' bookmark when only bottom
621 // (document level) pit was saved. Because of this, bookmark
622 // restoration is inaccurate. If a bookmark was within an inset,
623 // it will be restored to the left of the outmost inset that contains
625 if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
626 doc_it = doc_iterator_begin(buffer_.inset());
627 doc_it.pit() = bottom_pit;
628 doc_it.pos() = min(bottom_pos, doc_it.paragraph().size());
633 // Note: only bottom (document) level pit is set.
635 // set the current font.
636 d->cursor_.setCurrentFont();
637 // To center the screen on this new position we need the
638 // paragraph position which is computed at draw() time.
639 // So we need a redraw!
649 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
651 if (lyxrc.rtl_support) {
652 if (d->cursor_.real_current_font.isRightToLeft()) {
653 if (d->intl_.keymap == Intl::PRIMARY)
654 d->intl_.keyMapSec();
656 if (d->intl_.keymap == Intl::SECONDARY)
657 d->intl_.keyMapPrim();
661 d->intl_.getTransManager().translateAndInsert(c, t, cur);
665 int BufferView::workWidth() const
671 void BufferView::showCursor()
673 // We are not properly started yet, delay until resizing is
678 LYXERR(Debug::SCROLLING, "recentering!");
680 CursorSlice & bot = d->cursor_.bottom();
681 TextMetrics & tm = d->text_metrics_[bot.text()];
683 int const bot_pit = d->cursor_.bottom().pit();
684 if (bot_pit == tm.first().first - 1)
685 tm.newParMetricsUp();
686 else if (bot_pit == tm.last().first + 1)
687 tm.newParMetricsDown();
689 if (tm.has(bot_pit)) {
690 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
691 int offset = coordOffset(d->cursor_, d->cursor_.boundary()).y_;
692 int ypos = pm.position() + offset;
693 Dimension const & row_dim = d->cursor_.textRow().dimension();
694 if (ypos - row_dim.ascent() < 0)
695 scrollUp(- ypos + row_dim.ascent());
696 else if (ypos + row_dim.descent() > height_)
697 scrollDown(ypos - height_ + row_dim.descent());
698 // else, nothing to do, the cursor is already visible so we just return.
702 tm.redoParagraph(bot_pit);
703 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
704 int offset = coordOffset(d->cursor_, d->cursor_.boundary()).y_;
706 d->anchor_pit_ = bot_pit;
707 Dimension const & row_dim = d->cursor_.textRow().dimension();
709 if (d->anchor_pit_ == 0)
710 d->anchor_ypos_ = offset + pm.ascent();
711 else if (d->anchor_pit_ >= pos_type(bot.text()->paragraphs().size() - 1)) {
712 d->anchor_pit_ = bot.text()->paragraphs().size() - 1;
713 d->anchor_ypos_ = height_ - offset - row_dim.descent();
715 d->anchor_ypos_ = offset + pm.ascent() - height_ / 2;
723 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
727 Cursor & cur = d->cursor_;
729 switch (cmd.action) {
732 flag.enabled(buffer_.undo().hasUndoStack());
735 flag.enabled(buffer_.undo().hasRedoStack());
737 case LFUN_FILE_INSERT:
738 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
739 case LFUN_FILE_INSERT_PLAINTEXT:
740 case LFUN_BOOKMARK_SAVE:
741 // FIXME: Actually, these LFUNS should be moved to Text
742 flag.enabled(cur.inTexted());
744 case LFUN_FONT_STATE:
745 case LFUN_LABEL_INSERT:
746 case LFUN_INFO_INSERT:
747 case LFUN_PARAGRAPH_GOTO:
749 case LFUN_REFERENCE_NEXT:
751 case LFUN_WORD_REPLACE:
754 case LFUN_MARK_TOGGLE:
755 case LFUN_SCREEN_RECENTER:
756 case LFUN_BIBTEX_DATABASE_ADD:
757 case LFUN_BIBTEX_DATABASE_DEL:
758 case LFUN_WORDS_COUNT:
759 case LFUN_NEXT_INSET_TOGGLE:
763 case LFUN_LABEL_GOTO: {
764 flag.enabled(!cmd.argument().empty()
765 || getInsetByCode<InsetRef>(cur, REF_CODE));
769 case LFUN_CHANGES_TRACK:
771 flag.setOnOff(buffer_.params().trackChanges);
774 case LFUN_CHANGES_OUTPUT:
776 flag.setOnOff(buffer_.params().outputChanges);
779 case LFUN_CHANGES_MERGE:
780 case LFUN_CHANGE_NEXT:
781 case LFUN_ALL_CHANGES_ACCEPT:
782 case LFUN_ALL_CHANGES_REJECT:
783 // TODO: context-sensitive enabling of LFUNs
784 // In principle, these command should only be enabled if there
785 // is a change in the document. However, without proper
786 // optimizations, this will inevitably result in poor performance.
790 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
791 flag.setOnOff(buffer_.params().compressed);
795 case LFUN_BUFFER_TOGGLE_EMBEDDING: {
796 flag.setOnOff(buffer_.params().embedded);
801 case LFUN_SCREEN_DOWN:
805 // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
806 // everywhere else before this can enabled:
807 case LFUN_SCREEN_UP_SELECT:
808 case LFUN_SCREEN_DOWN_SELECT:
812 case LFUN_LAYOUT_TABULAR:
813 flag.enabled(cur.innerInsetOfType(TABULAR_CODE));
817 case LFUN_LAYOUT_PARAGRAPH:
818 flag.enabled(cur.inset().forceDefaultParagraphs(cur.idx()));
821 case LFUN_INSET_SETTINGS: {
822 InsetCode code = cur.inset().lyxCode();
826 enable = cmd.argument() == "tabular";
829 enable = cmd.argument() == "ert";
832 enable = cmd.argument() == "float";
835 enable = cmd.argument() == "wrap";
838 enable = cmd.argument() == "note";
841 enable = cmd.argument() == "branch";
844 enable = cmd.argument() == "box";
847 enable = cmd.argument() == "listings";
852 flag.enabled(enable);
856 case LFUN_DIALOG_SHOW_NEW_INSET:
857 flag.enabled(cur.inset().lyxCode() != ERT_CODE &&
858 cur.inset().lyxCode() != LISTINGS_CODE);
859 if (cur.inset().lyxCode() == CAPTION_CODE) {
861 if (cur.inset().getStatus(cur, cmd, flag))
874 bool BufferView::dispatch(FuncRequest const & cmd)
876 //lyxerr << [ cmd = " << cmd << "]" << endl;
878 // Make sure that the cached BufferView is correct.
879 LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
880 << " arg[" << to_utf8(cmd.argument()) << ']'
881 << " x[" << cmd.x << ']'
882 << " y[" << cmd.y << ']'
883 << " button[" << cmd.button() << ']');
885 Cursor & cur = d->cursor_;
887 switch (cmd.action) {
890 cur.message(_("Undo"));
891 cur.clearSelection();
893 cur.message(_("No further undo information"));
897 cur.message(_("Redo"));
898 cur.clearSelection();
900 cur.message(_("No further redo information"));
903 case LFUN_FONT_STATE:
904 cur.message(cur.currentState());
907 case LFUN_BOOKMARK_SAVE:
908 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
911 case LFUN_LABEL_GOTO: {
912 docstring label = cmd.argument();
915 getInsetByCode<InsetRef>(d->cursor_,
918 label = inset->getParam("reference");
919 // persistent=false: use temp_bookmark
929 case LFUN_PARAGRAPH_GOTO: {
930 int const id = convert<int>(to_utf8(cmd.argument()));
932 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
933 b = theBufferList().next(b)) {
935 ParIterator par = b->getParFromID(id);
936 if (par == b->par_iterator_end()) {
937 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
939 LYXERR(Debug::INFO, "Paragraph " << par->id()
940 << " found in buffer `"
941 << b->absFileName() << "'.");
945 setCursor(makeDocIterator(par, 0));
947 // Switch to other buffer view and resend cmd
948 theLyXFunc().dispatch(FuncRequest(
949 LFUN_BUFFER_SWITCH, b->absFileName()));
950 theLyXFunc().dispatch(cmd);
960 gotoInset(this, NOTE_CODE, false);
963 case LFUN_REFERENCE_NEXT: {
964 vector<InsetCode> tmp;
965 tmp.push_back(LABEL_CODE);
966 tmp.push_back(REF_CODE);
967 gotoInset(this, tmp, true);
971 case LFUN_CHANGES_TRACK:
972 buffer_.params().trackChanges = !buffer_.params().trackChanges;
975 case LFUN_CHANGES_OUTPUT:
976 buffer_.params().outputChanges = !buffer_.params().outputChanges;
977 if (buffer_.params().outputChanges) {
978 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
979 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
980 LaTeXFeatures::isAvailable("xcolor");
982 if (!dvipost && !xcolorsoul) {
983 Alert::warning(_("Changes not shown in LaTeX output"),
984 _("Changes will not be highlighted in LaTeX output, "
985 "because neither dvipost nor xcolor/soul are installed.\n"
986 "Please install these packages or redefine "
987 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
988 } else if (!xcolorsoul) {
989 Alert::warning(_("Changes not shown in LaTeX output"),
990 _("Changes will not be highlighted in LaTeX output "
991 "when using pdflatex, because xcolor and soul are not installed.\n"
992 "Please install both packages or redefine "
993 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
998 case LFUN_CHANGE_NEXT:
999 findNextChange(this);
1002 case LFUN_CHANGES_MERGE:
1003 if (findNextChange(this))
1004 showDialog("changes");
1007 case LFUN_ALL_CHANGES_ACCEPT:
1008 // select complete document
1009 d->cursor_.reset(buffer_.inset());
1010 d->cursor_.selHandle(true);
1011 buffer_.text().cursorBottom(d->cursor_);
1012 // accept everything in a single step to support atomic undo
1013 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1016 case LFUN_ALL_CHANGES_REJECT:
1017 // select complete document
1018 d->cursor_.reset(buffer_.inset());
1019 d->cursor_.selHandle(true);
1020 buffer_.text().cursorBottom(d->cursor_);
1021 // reject everything in a single step to support atomic undo
1022 // Note: reject does not work recursively; the user may have to repeat the operation
1023 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1026 case LFUN_WORD_FIND:
1030 case LFUN_WORD_REPLACE: {
1031 bool has_deleted = false;
1032 if (cur.selection()) {
1033 DocIterator beg = cur.selectionBegin();
1034 DocIterator end = cur.selectionEnd();
1035 if (beg.pit() == end.pit()) {
1036 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1037 if (cur.paragraph().isDeleted(p))
1042 replace(this, cmd, has_deleted);
1047 cur.clearSelection();
1049 cur.message(from_utf8(N_("Mark off")));
1053 cur.clearSelection();
1056 cur.message(from_utf8(N_("Mark on")));
1059 case LFUN_MARK_TOGGLE:
1060 cur.clearSelection();
1063 cur.message(from_utf8(N_("Mark removed")));
1066 cur.message(from_utf8(N_("Mark set")));
1071 case LFUN_SCREEN_RECENTER:
1075 case LFUN_BIBTEX_DATABASE_ADD: {
1076 Cursor tmpcur = d->cursor_;
1077 findInset(tmpcur, BIBTEX_CODE, false);
1078 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1081 if (inset->addDatabase(to_utf8(cmd.argument())))
1082 buffer_.updateBibfilesCache();
1087 case LFUN_BIBTEX_DATABASE_DEL: {
1088 Cursor tmpcur = d->cursor_;
1089 findInset(tmpcur, BIBTEX_CODE, false);
1090 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1093 if (inset->delDatabase(to_utf8(cmd.argument())))
1094 buffer_.updateBibfilesCache();
1099 case LFUN_WORDS_COUNT: {
1100 DocIterator from, to;
1101 if (cur.selection()) {
1102 from = cur.selectionBegin();
1103 to = cur.selectionEnd();
1105 from = doc_iterator_begin(buffer_.inset());
1106 to = doc_iterator_end(buffer_.inset());
1108 int const count = countWords(from, to);
1111 if (cur.selection())
1112 message = bformat(_("%1$d words in selection."),
1115 message = bformat(_("%1$d words in document."),
1119 if (cur.selection())
1120 message = _("One word in selection.");
1122 message = _("One word in document.");
1125 Alert::information(_("Count words"), message);
1129 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1130 // turn compression on/off
1131 buffer_.params().compressed = !buffer_.params().compressed;
1134 case LFUN_BUFFER_TOGGLE_EMBEDDING:
1135 // turn embedding on/off
1136 buffer_.embeddedFiles().enable(!buffer_.params().embedded);
1139 case LFUN_NEXT_INSET_TOGGLE: {
1140 // this is the real function we want to invoke
1141 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1142 // if there is an inset at cursor, see whether it
1144 Inset * inset = cur.nextInset();
1146 if (inset->isActive()) {
1147 Cursor tmpcur = cur;
1148 tmpcur.pushBackward(*inset);
1149 inset->dispatch(tmpcur, tmpcmd);
1150 if (tmpcur.result().dispatched()) {
1153 } else if (inset->editable() == Inset::IS_EDITABLE) {
1154 inset->edit(cur, true);
1157 // if it did not work, try the underlying inset.
1158 if (!cur.result().dispatched())
1159 cur.dispatch(tmpcmd);
1161 if (cur.result().dispatched())
1162 cur.clearSelection();
1167 case LFUN_SCREEN_UP:
1168 case LFUN_SCREEN_DOWN: {
1169 Point p = getPos(cur, cur.boundary());
1170 if (p.y_ < 0 || p.y_ > height_) {
1171 // The cursor is off-screen so recenter before proceeding.
1173 p = getPos(cur, cur.boundary());
1175 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1176 cur.reset(buffer_.inset());
1177 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1178 //FIXME: what to do with cur.x_target()?
1183 case LFUN_SCREEN_UP_SELECT:
1184 case LFUN_SCREEN_DOWN_SELECT: {
1185 // Those two are not ready yet for consumption.
1188 cur.selHandle(true);
1189 size_t initial_depth = cur.depth();
1190 Point const p = getPos(cur, cur.boundary());
1191 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1192 // FIXME: We need to verify if the cursor stayed within an inset...
1193 //cur.reset(buffer_.inset());
1194 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1196 while (cur.depth() > initial_depth) {
1199 // FIXME: we need to do a redraw again because of the selection
1200 // But no screen update is needed.
1201 d->update_strategy_ = NoScreenUpdate;
1214 docstring const BufferView::requestSelection()
1216 Cursor & cur = d->cursor_;
1218 if (!cur.selection()) {
1219 d->xsel_cache_.set = false;
1223 if (!d->xsel_cache_.set ||
1224 cur.top() != d->xsel_cache_.cursor ||
1225 cur.anchor_.top() != d->xsel_cache_.anchor)
1227 d->xsel_cache_.cursor = cur.top();
1228 d->xsel_cache_.anchor = cur.anchor_.top();
1229 d->xsel_cache_.set = cur.selection();
1230 return cur.selectionAsString(false);
1236 void BufferView::clearSelection()
1238 d->cursor_.clearSelection();
1239 // Clear the selection buffer. Otherwise a subsequent
1240 // middle-mouse-button paste would use the selection buffer,
1241 // not the more current external selection.
1242 cap::clearSelection();
1243 d->xsel_cache_.set = false;
1244 // The buffer did not really change, but this causes the
1245 // redraw we need because we cleared the selection above.
1250 void BufferView::resize(int width, int height)
1252 // Update from work area
1256 // Clear the paragraph height cache.
1257 d->par_height_.clear();
1263 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1265 TextMetrics & tm = d->text_metrics_[&text];
1266 Inset * inset = tm.checkInsetHit(x, y);
1270 if (!inset->descendable())
1271 // No need to go further down if the inset is not
1275 size_t cell_number = inset->nargs();
1276 // Check all the inner cell.
1277 for (size_t i = 0; i != cell_number; ++i) {
1278 Text const * inner_text = inset->getText(i);
1281 Inset const * inset_deeper =
1282 getCoveringInset(*inner_text, x, y);
1284 return inset_deeper;
1292 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1294 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1296 // This is only called for mouse related events including
1297 // LFUN_FILE_OPEN generated by drag-and-drop.
1298 FuncRequest cmd = cmd0;
1301 cur.push(buffer_.inset());
1302 cur.selection() = d->cursor_.selection();
1304 // Either the inset under the cursor or the
1305 // surrounding Text will handle this event.
1307 // make sure we stay within the screen...
1308 cmd.y = min(max(cmd.y, -1), height_);
1310 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1312 // Get inset under mouse, if there is one.
1313 Inset const * covering_inset =
1314 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1315 if (covering_inset == d->last_inset_)
1316 // Same inset, no need to do anything...
1319 bool need_redraw = false;
1320 // const_cast because of setMouseHover().
1321 Inset * inset = const_cast<Inset *>(covering_inset);
1323 // Remove the hint on the last hovered inset (if any).
1324 need_redraw |= d->last_inset_->setMouseHover(false);
1326 // Highlighted the newly hovered inset (if any).
1327 need_redraw |= inset->setMouseHover(true);
1328 d->last_inset_ = inset;
1332 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1333 << cmd.x << ", " << cmd.y << ")");
1335 d->update_strategy_ = DecorationUpdate;
1337 // This event (moving without mouse click) is not passed further.
1338 // This should be changed if it is further utilized.
1343 // Build temporary cursor.
1344 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1346 // Put anchor at the same position.
1349 // Try to dispatch to an non-editable inset near this position
1350 // via the temp cursor. If the inset wishes to change the real
1351 // cursor it has to do so explicitly by using
1352 // cur.bv().cursor() = cur; (or similar)
1354 inset->dispatch(cur, cmd);
1356 // Now dispatch to the temporary cursor. If the real cursor should
1357 // be modified, the inset's dispatch has to do so explicitly.
1358 if (!cur.result().dispatched())
1361 //Do we have a selection?
1362 theSelection().haveSelection(cursor().selection());
1364 // If the command has been dispatched,
1365 if (cur.result().dispatched()
1366 // an update is asked,
1367 && cur.result().update())
1368 processUpdateFlags(cur.result().update());
1372 void BufferView::scroll(int y)
1381 void BufferView::scrollDown(int offset)
1383 Text * text = &buffer_.text();
1384 TextMetrics & tm = d->text_metrics_[text];
1385 int ymax = height_ + offset;
1387 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1388 int bottom_pos = last.second->position() + last.second->descent();
1389 if (last.first + 1 == int(text->paragraphs().size())) {
1390 if (bottom_pos <= height_)
1392 offset = min(offset, bottom_pos - height_);
1395 if (bottom_pos > ymax)
1397 tm.newParMetricsDown();
1399 d->anchor_ypos_ -= offset;
1405 void BufferView::scrollUp(int offset)
1407 Text * text = &buffer_.text();
1408 TextMetrics & tm = d->text_metrics_[text];
1409 int ymin = - offset;
1411 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1412 int top_pos = first.second->position() - first.second->ascent();
1413 if (first.first == 0) {
1416 offset = min(offset, - top_pos);
1421 tm.newParMetricsUp();
1423 d->anchor_ypos_ += offset;
1429 void BufferView::setCursorFromRow(int row)
1434 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1436 d->cursor_.reset(buffer_.inset());
1438 buffer_.text().setCursor(d->cursor_, 0, 0);
1440 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1444 void BufferView::gotoLabel(docstring const & label)
1446 for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1447 vector<docstring> labels;
1448 it->getLabelList(buffer_, labels);
1449 if (find(labels.begin(), labels.end(), label) != labels.end()) {
1451 processUpdateFlags(Update::FitCursor);
1458 TextMetrics const & BufferView::textMetrics(Text const * t) const
1460 return const_cast<BufferView *>(this)->textMetrics(t);
1464 TextMetrics & BufferView::textMetrics(Text const * t)
1466 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
1467 if (tmc_it == d->text_metrics_.end()) {
1468 tmc_it = d->text_metrics_.insert(
1469 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1471 return tmc_it->second;
1475 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1478 return textMetrics(t).parMetrics(pit);
1482 int BufferView::workHeight() const
1488 void BufferView::setCursor(DocIterator const & dit)
1490 size_t const n = dit.depth();
1491 for (size_t i = 0; i < n; ++i)
1492 dit[i].inset().edit(d->cursor_, true);
1494 d->cursor_.setCursor(dit);
1495 d->cursor_.selection() = false;
1499 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1501 // Would be wrong to delete anything if we have a selection.
1502 if (cur.selection())
1505 bool need_anchor_change = false;
1506 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1507 need_anchor_change);
1509 if (need_anchor_change)
1515 updateLabels(buffer_);
1523 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1525 BOOST_ASSERT(&cur.bv() == this);
1528 // this event will clear selection so we save selection for
1529 // persistent selection
1530 cap::saveSelection(cursor());
1532 // Has the cursor just left the inset?
1533 bool badcursor = false;
1534 bool leftinset = (&d->cursor_.inset() != &cur.inset());
1536 badcursor = notifyCursorLeaves(d->cursor_, cur);
1538 // FIXME: shift-mouse selection doesn't work well across insets.
1539 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1541 // do the dEPM magic if needed
1542 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1543 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1544 // the leftinset bool would not be necessary (badcursor instead).
1545 bool update = leftinset;
1546 if (!do_selection && !badcursor && d->cursor_.inTexted())
1547 update |= checkDepm(cur, d->cursor_);
1549 // if the cursor was in an empty script inset and the new
1550 // position is in the nucleus of the inset, notifyCursorLeaves
1551 // will kill the script inset itself. So we check all the
1552 // elements of the cursor to make sure that they are correct.
1553 // For an example, see bug 2933:
1554 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1555 // The code below could maybe be moved to a DocIterator method.
1556 //lyxerr << "cur before " << cur <<endl;
1557 DocIterator dit(cur.inset());
1558 dit.push_back(cur.bottom());
1560 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1561 dit.push_back(cur[i]);
1564 //lyxerr << "5 cur after" << dit <<endl;
1566 d->cursor_.setCursor(dit);
1567 d->cursor_.boundary(cur.boundary());
1569 d->cursor_.setSelection();
1571 d->cursor_.clearSelection();
1573 d->cursor_.finishUndo();
1574 d->cursor_.setCurrentFont();
1579 void BufferView::putSelectionAt(DocIterator const & cur,
1580 int length, bool backwards)
1582 d->cursor_.clearSelection();
1588 d->cursor_.pos() += length;
1589 d->cursor_.setSelection(d->cursor_, -length);
1591 d->cursor_.setSelection(d->cursor_, length);
1596 Cursor & BufferView::cursor()
1602 Cursor const & BufferView::cursor() const
1608 pit_type BufferView::anchor_ref() const
1610 return d->anchor_pit_;
1614 bool BufferView::singleParUpdate()
1616 Text & buftext = buffer_.text();
1617 pit_type const bottom_pit = d->cursor_.bottom().pit();
1618 TextMetrics & tm = textMetrics(&buftext);
1619 int old_height = tm.parMetrics(bottom_pit).height();
1621 // In Single Paragraph mode, rebreak only
1622 // the (main text, not inset!) paragraph containing the cursor.
1623 // (if this paragraph contains insets etc., rebreaking will
1624 // recursively descend)
1625 tm.redoParagraph(bottom_pit);
1626 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
1627 if (pm.height() != old_height)
1628 // Paragraph height has changed so we cannot proceed to
1629 // the singlePar optimisation.
1632 d->update_strategy_ = SingleParUpdate;
1634 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
1635 << " y2: " << pm.position() + pm.descent()
1636 << " pit: " << bottom_pit
1637 << " singlepar: 1");
1642 void BufferView::updateMetrics()
1644 Text & buftext = buffer_.text();
1645 pit_type const npit = int(buftext.paragraphs().size());
1647 // Clear out the position cache in case of full screen redraw,
1648 d->coord_cache_.clear();
1650 // Clear out paragraph metrics to avoid having invalid metrics
1651 // in the cache from paragraphs not relayouted below
1652 // The complete text metrics will be redone.
1653 d->text_metrics_.clear();
1655 TextMetrics & tm = textMetrics(&buftext);
1657 // Rebreak anchor paragraph.
1658 tm.redoParagraph(d->anchor_pit_);
1659 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
1660 anchor_pm.setPosition(d->anchor_ypos_);
1662 LYXERR(Debug::PAINTING, "metrics: "
1663 << " anchor pit = " << d->anchor_pit_
1664 << " anchor ypos = " << d->anchor_ypos_);
1666 // Redo paragraphs above anchor if necessary.
1667 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
1668 // We are now just above the anchor paragraph.
1669 pit_type pit1 = d->anchor_pit_ - 1;
1670 for (; pit1 >= 0 && y1 > 0; --pit1) {
1671 tm.redoParagraph(pit1);
1672 ParagraphMetrics & pm = tm.par_metrics_[pit1];
1674 // Save the paragraph position in the cache.
1679 // Redo paragraphs below the anchor if necessary.
1680 int y2 = d->anchor_ypos_ + anchor_pm.descent();
1681 // We are now just below the anchor paragraph.
1682 pit_type pit2 = d->anchor_pit_ + 1;
1683 for (; pit2 < npit && y2 < height_; ++pit2) {
1684 tm.redoParagraph(pit2);
1685 ParagraphMetrics & pm = tm.par_metrics_[pit2];
1687 // Save the paragraph position in the cache.
1692 LYXERR(Debug::PAINTING, "Metrics: "
1693 << " anchor pit = " << d->anchor_pit_
1694 << " anchor ypos = " << d->anchor_ypos_
1697 << " pit1 = " << pit1
1698 << " pit2 = " << pit2);
1700 d->update_strategy_ = FullScreenUpdate;
1702 if (lyxerr.debugging(Debug::WORKAREA)) {
1703 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
1704 d->coord_cache_.dump();
1709 void BufferView::insertLyXFile(FileName const & fname)
1711 BOOST_ASSERT(d->cursor_.inTexted());
1713 // Get absolute path of file and add ".lyx"
1714 // to the filename if necessary
1715 FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
1717 docstring const disp_fn = makeDisplayPath(filename.absFilename());
1718 // emit message signal.
1719 message(bformat(_("Inserting document %1$s..."), disp_fn));
1722 Buffer buf("", false);
1723 if (buf.loadLyXFile(filename)) {
1724 ErrorList & el = buffer_.errorList("Parse");
1725 // Copy the inserted document error list into the current buffer one.
1726 el = buf.errorList("Parse");
1727 buffer_.undo().recordUndo(d->cursor_);
1728 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
1729 buf.params().getTextClassPtr(), el);
1730 res = _("Document %1$s inserted.");
1732 res = _("Could not insert document %1$s");
1737 // emit message signal.
1738 message(bformat(res, disp_fn));
1739 buffer_.errors("Parse");
1743 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1749 // Addup contribution of nested insets, from inside to outside,
1750 // keeping the outer paragraph for a special handling below
1751 for (size_t i = dit.depth() - 1; i >= 1; --i) {
1752 CursorSlice const & sl = dit[i];
1756 // get relative position inside sl.inset()
1757 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
1759 // Make relative position inside of the edited inset relative to sl.inset()
1763 // In case of an RTL inset, the edited inset will be positioned to the left
1766 bool boundary_i = boundary && i + 1 == dit.depth();
1767 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
1772 // remember width for the case that sl.inset() is positioned in an RTL inset
1773 if (i && dit[i - 1].text()) {
1774 // If this Inset is inside a Text Inset, retrieve the Dimension
1775 // from the containing text instead of using Inset::dimension() which
1776 // might not be implemented.
1777 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
1778 // elimination of Inset::dim_ cache. This coordOffset() method needs
1779 // to be rewritten in light of the new design.
1780 Dimension const & dim = parMetrics(dit[i - 1].text(),
1781 dit[i - 1].pit()).insetDimension(&sl.inset());
1784 Dimension const dim = sl.inset().dimension(*this);
1788 //lyxerr << "Cursor::getPos, i: "
1789 // << i << " x: " << xx << " y: " << y << endl;
1792 // Add contribution of initial rows of outermost paragraph
1793 CursorSlice const & sl = dit[0];
1794 TextMetrics const & tm = textMetrics(sl.text());
1795 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
1796 BOOST_ASSERT(!pm.rows().empty());
1797 y -= pm.rows()[0].ascent();
1799 // FIXME: document this mess
1801 if (sl.pos() > 0 && dit.depth() == 1) {
1803 if (pos && boundary)
1805 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
1806 rend = pm.pos2row(pos);
1808 rend = pm.pos2row(sl.pos());
1810 size_t rend = pm.pos2row(sl.pos());
1812 for (size_t rit = 0; rit != rend; ++rit)
1813 y += pm.rows()[rit].height();
1814 y += pm.rows()[rend].ascent();
1816 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
1818 // Make relative position from the nested inset now bufferview absolute.
1819 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
1822 // In the RTL case place the nested inset at the left of the cursor in
1823 // the outer paragraph
1824 bool boundary_1 = boundary && 1 == dit.depth();
1825 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
1833 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
1835 CursorSlice const & bot = dit.bottom();
1836 TextMetrics const & tm = textMetrics(bot.text());
1837 if (!tm.has(bot.pit()))
1838 return Point(-1, -1);
1840 Point p = coordOffset(dit, boundary); // offset from outer paragraph
1841 p.y_ += tm.parMetrics(bot.pit()).position();
1846 void BufferView::draw(frontend::Painter & pain)
1848 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
1849 Text & text = buffer_.text();
1850 TextMetrics const & tm = d->text_metrics_[&text];
1851 int const y = tm.first().second->position();
1852 PainterInfo pi(this, pain);
1854 switch (d->update_strategy_) {
1856 case NoScreenUpdate:
1857 // If no screen painting is actually needed, only some the different
1858 // coordinates of insets and paragraphs needs to be updated.
1859 pi.full_repaint = true;
1860 pi.pain.setDrawingEnabled(false);
1864 case SingleParUpdate:
1865 pi.full_repaint = false;
1866 // In general, only the current row of the outermost paragraph
1867 // will be redrawn. Particular cases where selection spans
1868 // multiple paragraph are correctly detected in TextMetrics.
1872 case DecorationUpdate:
1873 // FIXME: We should also distinguish DecorationUpdate to avoid text
1874 // drawing if possible. This is not possible to do easily right now
1875 // because of the single backing pixmap.
1877 case FullScreenUpdate:
1878 // The whole screen, including insets, will be refreshed.
1879 pi.full_repaint = true;
1881 // Clear background.
1882 pain.fillRectangle(0, 0, width_, height_,
1883 buffer_.inset().backgroundColor());
1888 // and possibly grey out below
1889 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1890 int const y2 = lastpm.second->position() + lastpm.second->descent();
1892 pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
1895 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
1897 // The scrollbar needs an update.
1900 // Normalize anchor for next time
1901 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
1902 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1903 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
1904 ParagraphMetrics const & pm = tm.parMetrics(pit);
1905 if (pm.position() + pm.descent() > 0) {
1906 d->anchor_pit_ = pit;
1907 d->anchor_ypos_ = pm.position();
1911 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
1912 << " anchor ypos = " << d->anchor_ypos_);
1916 void BufferView::message(docstring const & msg)
1919 d->gui_->message(msg);
1923 void BufferView::showDialog(string const & name)
1926 d->gui_->showDialog(name, string());
1930 void BufferView::showDialog(string const & name,
1931 string const & data, Inset * inset)
1934 d->gui_->showDialog(name, data, inset);
1938 void BufferView::updateDialog(string const & name, string const & data)
1941 d->gui_->updateDialog(name, data);
1945 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
1951 // FIXME: Move this out of BufferView again
1952 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
1954 if (!fname.isReadableFile()) {
1955 docstring const error = from_ascii(strerror(errno));
1956 docstring const file = makeDisplayPath(fname.absFilename(), 50);
1957 docstring const text =
1958 bformat(_("Could not read the specified document\n"
1959 "%1$s\ndue to the error: %2$s"), file, error);
1960 Alert::error(_("Could not read file"), text);
1964 if (!fname.isReadableFile()) {
1965 docstring const file = makeDisplayPath(fname.absFilename(), 50);
1966 docstring const text =
1967 bformat(_("%1$s\n is not readable."), file);
1968 Alert::error(_("Could not open file"), text);
1972 // FIXME UNICODE: We don't know the encoding of the file
1973 docstring file_content = fname.fileContents("UTF-8");
1974 if (file_content.empty()) {
1975 Alert::error(_("Reading not UTF-8 encoded file"),
1976 _("The file is not UTF-8 encoded.\n"
1977 "It will be read as local 8Bit-encoded.\n"
1978 "If this does not give the correct result\n"
1979 "then please change the encoding of the file\n"
1980 "to UTF-8 with a program other than LyX.\n"));
1981 file_content = fname.fileContents("local8bit");
1984 return normalize_c(file_content);
1988 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
1990 docstring const tmpstr = contentsOfPlaintextFile(f);
1995 Cursor & cur = cursor();
1996 cap::replaceSelection(cur);
1997 buffer_.undo().recordUndo(cur);
1999 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2001 cur.innerText()->insertStringAsLines(cur, tmpstr);