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_ref_(0), offset_ref_(0), need_centering_(false),
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_ref_;
237 bool need_centering_;
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_)
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 // Update macro store
354 if (!(cursor().inMathed() && cursor().inMacroMode()))
355 buffer_.updateMacros();
357 // Now do the first drawing step if needed. This consists on updating
358 // the CoordCache in updateMetrics().
359 // The second drawing step is done in WorkArea::redraw() if needed.
361 // Case when no explicit update is requested.
363 // no need to redraw anything.
364 d->update_strategy_ = NoScreenUpdate;
368 if (flags == Update::Decoration) {
369 d->update_strategy_ = DecorationUpdate;
374 if (flags == Update::FitCursor
375 || flags == (Update::Decoration | Update::FitCursor)) {
376 bool const fit_cursor = fitCursor();
377 // tell the frontend to update the screen if needed.
383 if (flags & Update::Decoration) {
384 d->update_strategy_ = DecorationUpdate;
388 // no screen update is needed.
389 d->update_strategy_ = NoScreenUpdate;
393 bool const full_metrics = flags & Update::Force;
395 if (full_metrics || !singleParUpdate()) {
396 if (flags & Update::FitCursor) {
397 CursorSlice const & bot = d->cursor_.bottom();
398 TextMetrics const & tm = d->text_metrics_[bot.text()];
399 if (!tm.has(bot.pit()))
402 // We have to update the full screen metrics.
406 if (!(flags & Update::FitCursor)) {
411 //FIXME: updateMetrics() does not update paragraph position
412 // This is done at draw() time. So we need a redraw!
416 // The screen has already been updated thanks to the
417 // 'buffer_.changed()' call three line above. So no need
421 // The screen has been recentered around the cursor position so
428 void BufferView::updateScrollbar()
430 Text & t = buffer_.text();
431 TextMetrics & tm = d->text_metrics_[&t];
433 int const parsize = int(t.paragraphs().size() - 1);
434 if (d->anchor_ref_ > parsize) {
435 d->anchor_ref_ = parsize;
439 LYXERR(Debug::GUI, " Updating scrollbar: height: "
440 << t.paragraphs().size()
441 << " curr par: " << d->cursor_.bottom().pit()
442 << " default height " << defaultRowHeight());
444 // It would be better to fix the scrollbar to understand
445 // values in [0..1] and divide everything by wh
447 // estimated average paragraph height:
449 d->wh_ = height_ / 4;
451 int h = tm.parMetrics(d->anchor_ref_).height();
453 // Normalize anchor/offset (MV):
454 while (d->offset_ref_ > h && d->anchor_ref_ < parsize) {
457 h = tm.parMetrics(d->anchor_ref_).height();
459 // Look at paragraph heights on-screen
462 for (pit_type pit = d->anchor_ref_; pit <= parsize; ++pit) {
465 int const h2 = tm.parMetrics(pit).height();
471 int const hav = sumh / nh;
472 // More realistic average paragraph height
477 d->scrollbarParameters_.height = (parsize + 1) * d->wh_;
478 d->scrollbarParameters_.position = d->anchor_ref_ * d->wh_ + int(d->offset_ref_ * d->wh_ / float(h));
479 d->scrollbarParameters_.lineScrollHeight = int(d->wh_ * defaultRowHeight() / float(h));
483 ScrollbarParameters const & BufferView::scrollbarParameters() const
485 return d->scrollbarParameters_;
489 void BufferView::scrollDocView(int value)
491 LYXERR(Debug::GUI, "[ value = " << value << "]");
493 Text & t = buffer_.text();
494 TextMetrics & tm = d->text_metrics_[&t];
496 float const bar = value / float(d->wh_ * t.paragraphs().size());
498 d->anchor_ref_ = int(bar * t.paragraphs().size());
499 if (d->anchor_ref_ > int(t.paragraphs().size()) - 1)
500 d->anchor_ref_ = int(t.paragraphs().size()) - 1;
502 tm.redoParagraph(d->anchor_ref_);
503 int const h = tm.parMetrics(d->anchor_ref_).height();
504 d->offset_ref_ = int((bar * t.paragraphs().size() - d->anchor_ref_) * h);
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!
642 // We need another redraw because of the screen recentering.
650 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
652 if (lyxrc.rtl_support) {
653 if (d->cursor_.real_current_font.isRightToLeft()) {
654 if (d->intl_.keymap == Intl::PRIMARY)
655 d->intl_.keyMapSec();
657 if (d->intl_.keymap == Intl::SECONDARY)
658 d->intl_.keyMapPrim();
662 d->intl_.getTransManager().translateAndInsert(c, t, cur);
666 int BufferView::workWidth() const
672 void BufferView::updateOffsetRef()
674 // No need to update d->offset_ref_ in this case.
675 if (!d->need_centering_)
678 // We are not properly started yet, delay until resizing is
683 d->need_centering_ = false;
685 CursorSlice & bot = d->cursor_.bottom();
686 TextMetrics & tm = d->text_metrics_[bot.text()];
687 ParagraphMetrics const & pm = tm.parMetrics(bot.pit());
688 if (d->anchor_ref_ == 0)
690 else if (d->anchor_ref_ >= pos_type(bot.text()->paragraphs().size() - 1)) {
691 d->anchor_ref_ = bot.text()->paragraphs().size() - 1;
692 d->offset_ref_ = pm.height() - height_;
694 int y = coordOffset(d->cursor_, d->cursor_.boundary()).y_;
695 d->offset_ref_ = y + pm.ascent() - height_ / 2;
700 void BufferView::center()
702 d->anchor_ref_ = d->cursor_.bottom().pit();
703 d->need_centering_ = true;
707 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
711 Cursor & cur = d->cursor_;
713 switch (cmd.action) {
716 flag.enabled(buffer_.undo().hasUndoStack());
719 flag.enabled(buffer_.undo().hasRedoStack());
721 case LFUN_FILE_INSERT:
722 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
723 case LFUN_FILE_INSERT_PLAINTEXT:
724 case LFUN_BOOKMARK_SAVE:
725 // FIXME: Actually, these LFUNS should be moved to Text
726 flag.enabled(cur.inTexted());
728 case LFUN_FONT_STATE:
729 case LFUN_LABEL_INSERT:
730 case LFUN_INFO_INSERT:
731 case LFUN_PARAGRAPH_GOTO:
733 case LFUN_REFERENCE_NEXT:
735 case LFUN_WORD_REPLACE:
738 case LFUN_MARK_TOGGLE:
739 case LFUN_SCREEN_RECENTER:
740 case LFUN_BIBTEX_DATABASE_ADD:
741 case LFUN_BIBTEX_DATABASE_DEL:
742 case LFUN_WORDS_COUNT:
743 case LFUN_NEXT_INSET_TOGGLE:
747 case LFUN_LABEL_GOTO: {
748 flag.enabled(!cmd.argument().empty()
749 || getInsetByCode<InsetRef>(cur, REF_CODE));
753 case LFUN_CHANGES_TRACK:
755 flag.setOnOff(buffer_.params().trackChanges);
758 case LFUN_CHANGES_OUTPUT:
760 flag.setOnOff(buffer_.params().outputChanges);
763 case LFUN_CHANGES_MERGE:
764 case LFUN_CHANGE_NEXT:
765 case LFUN_ALL_CHANGES_ACCEPT:
766 case LFUN_ALL_CHANGES_REJECT:
767 // TODO: context-sensitive enabling of LFUNs
768 // In principle, these command should only be enabled if there
769 // is a change in the document. However, without proper
770 // optimizations, this will inevitably result in poor performance.
774 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
775 flag.setOnOff(buffer_.params().compressed);
779 case LFUN_BUFFER_TOGGLE_EMBEDDING: {
780 flag.setOnOff(buffer_.params().embedded);
785 case LFUN_SCREEN_DOWN:
789 // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
790 // everywhere else before this can enabled:
791 case LFUN_SCREEN_UP_SELECT:
792 case LFUN_SCREEN_DOWN_SELECT:
796 case LFUN_LAYOUT_TABULAR:
797 flag.enabled(cur.innerInsetOfType(TABULAR_CODE));
801 case LFUN_LAYOUT_PARAGRAPH:
802 flag.enabled(cur.inset().forceDefaultParagraphs(cur.idx()));
805 case LFUN_INSET_SETTINGS: {
806 InsetCode code = cur.inset().lyxCode();
810 enable = cmd.argument() == "tabular";
813 enable = cmd.argument() == "ert";
816 enable = cmd.argument() == "float";
819 enable = cmd.argument() == "wrap";
822 enable = cmd.argument() == "note";
825 enable = cmd.argument() == "branch";
828 enable = cmd.argument() == "box";
831 enable = cmd.argument() == "listings";
836 flag.enabled(enable);
840 case LFUN_DIALOG_SHOW_NEW_INSET:
841 flag.enabled(cur.inset().lyxCode() != ERT_CODE &&
842 cur.inset().lyxCode() != LISTINGS_CODE);
843 if (cur.inset().lyxCode() == CAPTION_CODE) {
845 if (cur.inset().getStatus(cur, cmd, flag))
858 Update::flags BufferView::dispatch(FuncRequest const & cmd)
860 //lyxerr << [ cmd = " << cmd << "]" << endl;
862 // Make sure that the cached BufferView is correct.
863 LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
864 << " arg[" << to_utf8(cmd.argument()) << ']'
865 << " x[" << cmd.x << ']'
866 << " y[" << cmd.y << ']'
867 << " button[" << cmd.button() << ']');
869 Cursor & cur = d->cursor_;
870 // Default Update flags.
871 Update::flags updateFlags = Update::Force | Update::FitCursor;
873 switch (cmd.action) {
876 cur.message(_("Undo"));
877 cur.clearSelection();
878 if (!cur.textUndo()) {
879 cur.message(_("No further undo information"));
880 updateFlags = Update::None;
885 cur.message(_("Redo"));
886 cur.clearSelection();
887 if (!cur.textRedo()) {
888 cur.message(_("No further redo information"));
889 updateFlags = Update::None;
893 case LFUN_FONT_STATE:
894 cur.message(cur.currentState());
897 case LFUN_BOOKMARK_SAVE:
898 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
901 case LFUN_LABEL_GOTO: {
902 docstring label = cmd.argument();
905 getInsetByCode<InsetRef>(d->cursor_,
908 label = inset->getParam("reference");
909 // persistent=false: use temp_bookmark
919 case LFUN_PARAGRAPH_GOTO: {
920 int const id = convert<int>(to_utf8(cmd.argument()));
922 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
923 b = theBufferList().next(b)) {
925 ParIterator par = b->getParFromID(id);
926 if (par == b->par_iterator_end()) {
927 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
929 LYXERR(Debug::INFO, "Paragraph " << par->id()
930 << " found in buffer `"
931 << b->absFileName() << "'.");
935 setCursor(makeDocIterator(par, 0));
937 // Switch to other buffer view and resend cmd
938 theLyXFunc().dispatch(FuncRequest(
939 LFUN_BUFFER_SWITCH, b->absFileName()));
940 theLyXFunc().dispatch(cmd);
941 updateFlags = Update::None;
951 gotoInset(this, NOTE_CODE, false);
954 case LFUN_REFERENCE_NEXT: {
955 vector<InsetCode> tmp;
956 tmp.push_back(LABEL_CODE);
957 tmp.push_back(REF_CODE);
958 gotoInset(this, tmp, true);
962 case LFUN_CHANGES_TRACK:
963 buffer_.params().trackChanges = !buffer_.params().trackChanges;
966 case LFUN_CHANGES_OUTPUT:
967 buffer_.params().outputChanges = !buffer_.params().outputChanges;
968 if (buffer_.params().outputChanges) {
969 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
970 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
971 LaTeXFeatures::isAvailable("xcolor");
973 if (!dvipost && !xcolorsoul) {
974 Alert::warning(_("Changes not shown in LaTeX output"),
975 _("Changes will not be highlighted in LaTeX output, "
976 "because neither dvipost nor xcolor/soul are installed.\n"
977 "Please install these packages or redefine "
978 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
979 } else if (!xcolorsoul) {
980 Alert::warning(_("Changes not shown in LaTeX output"),
981 _("Changes will not be highlighted in LaTeX output "
982 "when using pdflatex, because xcolor and soul are not installed.\n"
983 "Please install both packages or redefine "
984 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
989 case LFUN_CHANGE_NEXT:
990 findNextChange(this);
993 case LFUN_CHANGES_MERGE:
994 if (findNextChange(this))
995 showDialog("changes");
998 case LFUN_ALL_CHANGES_ACCEPT:
999 // select complete document
1000 d->cursor_.reset(buffer_.inset());
1001 d->cursor_.selHandle(true);
1002 buffer_.text().cursorBottom(d->cursor_);
1003 // accept everything in a single step to support atomic undo
1004 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1007 case LFUN_ALL_CHANGES_REJECT:
1008 // select complete document
1009 d->cursor_.reset(buffer_.inset());
1010 d->cursor_.selHandle(true);
1011 buffer_.text().cursorBottom(d->cursor_);
1012 // reject everything in a single step to support atomic undo
1013 // Note: reject does not work recursively; the user may have to repeat the operation
1014 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1017 case LFUN_WORD_FIND:
1021 case LFUN_WORD_REPLACE: {
1022 bool has_deleted = false;
1023 if (cur.selection()) {
1024 DocIterator beg = cur.selectionBegin();
1025 DocIterator end = cur.selectionEnd();
1026 if (beg.pit() == end.pit()) {
1027 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1028 if (cur.paragraph().isDeleted(p))
1033 replace(this, cmd, has_deleted);
1038 cur.clearSelection();
1040 cur.message(from_utf8(N_("Mark off")));
1044 cur.clearSelection();
1047 cur.message(from_utf8(N_("Mark on")));
1050 case LFUN_MARK_TOGGLE:
1051 cur.clearSelection();
1054 cur.message(from_utf8(N_("Mark removed")));
1057 cur.message(from_utf8(N_("Mark set")));
1062 case LFUN_SCREEN_RECENTER:
1066 case LFUN_BIBTEX_DATABASE_ADD: {
1067 Cursor tmpcur = d->cursor_;
1068 findInset(tmpcur, BIBTEX_CODE, false);
1069 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1072 if (inset->addDatabase(to_utf8(cmd.argument())))
1073 buffer_.updateBibfilesCache();
1078 case LFUN_BIBTEX_DATABASE_DEL: {
1079 Cursor tmpcur = d->cursor_;
1080 findInset(tmpcur, BIBTEX_CODE, false);
1081 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1084 if (inset->delDatabase(to_utf8(cmd.argument())))
1085 buffer_.updateBibfilesCache();
1090 case LFUN_WORDS_COUNT: {
1091 DocIterator from, to;
1092 if (cur.selection()) {
1093 from = cur.selectionBegin();
1094 to = cur.selectionEnd();
1096 from = doc_iterator_begin(buffer_.inset());
1097 to = doc_iterator_end(buffer_.inset());
1099 int const count = countWords(from, to);
1102 if (cur.selection())
1103 message = bformat(_("%1$d words in selection."),
1106 message = bformat(_("%1$d words in document."),
1110 if (cur.selection())
1111 message = _("One word in selection.");
1113 message = _("One word in document.");
1116 Alert::information(_("Count words"), message);
1120 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1121 // turn compression on/off
1122 buffer_.params().compressed = !buffer_.params().compressed;
1125 case LFUN_BUFFER_TOGGLE_EMBEDDING:
1126 // turn embedding on/off
1127 buffer_.embeddedFiles().enable(!buffer_.params().embedded);
1130 case LFUN_NEXT_INSET_TOGGLE: {
1131 // this is the real function we want to invoke
1132 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1133 // if there is an inset at cursor, see whether it
1135 Inset * inset = cur.nextInset();
1137 if (inset->isActive()) {
1138 Cursor tmpcur = cur;
1139 tmpcur.pushBackward(*inset);
1140 inset->dispatch(tmpcur, tmpcmd);
1141 if (tmpcur.result().dispatched()) {
1144 } else if (inset->editable() == Inset::IS_EDITABLE) {
1145 inset->edit(cur, true);
1148 // if it did not work, try the underlying inset.
1149 if (!cur.result().dispatched())
1150 cur.dispatch(tmpcmd);
1152 if (cur.result().dispatched())
1153 cur.clearSelection();
1158 case LFUN_SCREEN_UP:
1159 case LFUN_SCREEN_DOWN: {
1160 Point p = getPos(cur, cur.boundary());
1161 if (p.y_ < 0 || p.y_ > height_) {
1162 // The cursor is off-screen so recenter before proceeding.
1165 //FIXME: updateMetrics() does not update paragraph position
1166 // This is done at draw() time. So we need a redraw!
1167 // But no screen update is needed.
1168 d->update_strategy_ = NoScreenUpdate;
1170 p = getPos(cur, cur.boundary());
1172 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1173 cur.reset(buffer_.inset());
1174 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1175 //FIXME: what to do with cur.x_target()?
1177 // The metrics are already up to date. see scroll()
1178 updateFlags = Update::None;
1182 case LFUN_SCREEN_UP_SELECT:
1183 case LFUN_SCREEN_DOWN_SELECT: {
1184 cur.selHandle(true);
1185 size_t initial_depth = cur.depth();
1186 Point const p = getPos(cur, cur.boundary());
1187 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1188 // FIXME: We need to verify if the cursor stayed within an inset...
1189 //cur.reset(buffer_.inset());
1190 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1192 while (cur.depth() > initial_depth) {
1195 // FIXME: we need to do a redraw again because of the selection
1196 // But no screen update is needed.
1197 d->update_strategy_ = NoScreenUpdate;
1199 updateFlags = Update::Force | Update::FitCursor;
1204 updateFlags = Update::None;
1211 docstring const BufferView::requestSelection()
1213 Cursor & cur = d->cursor_;
1215 if (!cur.selection()) {
1216 d->xsel_cache_.set = false;
1220 if (!d->xsel_cache_.set ||
1221 cur.top() != d->xsel_cache_.cursor ||
1222 cur.anchor_.top() != d->xsel_cache_.anchor)
1224 d->xsel_cache_.cursor = cur.top();
1225 d->xsel_cache_.anchor = cur.anchor_.top();
1226 d->xsel_cache_.set = cur.selection();
1227 return cur.selectionAsString(false);
1233 void BufferView::clearSelection()
1235 d->cursor_.clearSelection();
1236 // Clear the selection buffer. Otherwise a subsequent
1237 // middle-mouse-button paste would use the selection buffer,
1238 // not the more current external selection.
1239 cap::clearSelection();
1240 d->xsel_cache_.set = false;
1241 // The buffer did not really change, but this causes the
1242 // redraw we need because we cleared the selection above.
1247 void BufferView::resize(int width, int height)
1249 // Update from work area
1257 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1259 TextMetrics & tm = d->text_metrics_[&text];
1260 Inset * inset = tm.checkInsetHit(x, y);
1264 if (!inset->descendable())
1265 // No need to go further down if the inset is not
1269 size_t cell_number = inset->nargs();
1270 // Check all the inner cell.
1271 for (size_t i = 0; i != cell_number; ++i) {
1272 Text const * inner_text = inset->getText(i);
1275 Inset const * inset_deeper =
1276 getCoveringInset(*inner_text, x, y);
1278 return inset_deeper;
1286 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1288 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1290 // This is only called for mouse related events including
1291 // LFUN_FILE_OPEN generated by drag-and-drop.
1292 FuncRequest cmd = cmd0;
1295 cur.push(buffer_.inset());
1296 cur.selection() = d->cursor_.selection();
1298 // Either the inset under the cursor or the
1299 // surrounding Text will handle this event.
1301 // make sure we stay within the screen...
1302 cmd.y = min(max(cmd.y, -1), height_);
1304 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1306 // Get inset under mouse, if there is one.
1307 Inset const * covering_inset =
1308 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1309 if (covering_inset == d->last_inset_)
1310 // Same inset, no need to do anything...
1313 bool need_redraw = false;
1314 // const_cast because of setMouseHover().
1315 Inset * inset = const_cast<Inset *>(covering_inset);
1317 // Remove the hint on the last hovered inset (if any).
1318 need_redraw |= d->last_inset_->setMouseHover(false);
1320 // Highlighted the newly hovered inset (if any).
1321 need_redraw |= inset->setMouseHover(true);
1322 d->last_inset_ = inset;
1326 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1327 << cmd.x << ", " << cmd.y << ")");
1329 d->update_strategy_ = DecorationUpdate;
1331 // This event (moving without mouse click) is not passed further.
1332 // This should be changed if it is further utilized.
1337 // Build temporary cursor.
1338 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1340 // Put anchor at the same position.
1343 // Try to dispatch to an non-editable inset near this position
1344 // via the temp cursor. If the inset wishes to change the real
1345 // cursor it has to do so explicitly by using
1346 // cur.bv().cursor() = cur; (or similar)
1348 inset->dispatch(cur, cmd);
1350 // Now dispatch to the temporary cursor. If the real cursor should
1351 // be modified, the inset's dispatch has to do so explicitly.
1352 if (!cur.result().dispatched())
1355 //Do we have a selection?
1356 theSelection().haveSelection(cursor().selection());
1358 // If the command has been dispatched,
1359 if (cur.result().dispatched()
1360 // an update is asked,
1361 && cur.result().update())
1362 processUpdateFlags(cur.result().update());
1366 void BufferView::scroll(int y)
1375 void BufferView::scrollDown(int offset)
1377 Text * text = &buffer_.text();
1378 TextMetrics & tm = d->text_metrics_[text];
1379 int ymax = height_ + offset;
1381 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1382 int bottom_pos = last.second->position() + last.second->descent();
1383 if (last.first + 1 == int(text->paragraphs().size())) {
1384 if (bottom_pos <= height_)
1386 offset = min(offset, bottom_pos - height_);
1389 if (bottom_pos > ymax)
1391 tm.newParMetricsDown();
1393 d->offset_ref_ += offset;
1399 void BufferView::scrollUp(int offset)
1401 Text * text = &buffer_.text();
1402 TextMetrics & tm = d->text_metrics_[text];
1403 int ymin = - offset;
1405 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1406 int top_pos = first.second->position() - first.second->ascent();
1407 if (first.first == 0) {
1410 offset = min(offset, - top_pos);
1415 tm.newParMetricsUp();
1417 d->offset_ref_ -= offset;
1423 void BufferView::setCursorFromRow(int row)
1428 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1430 d->cursor_.reset(buffer_.inset());
1432 buffer_.text().setCursor(d->cursor_, 0, 0);
1434 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1438 void BufferView::gotoLabel(docstring const & label)
1440 for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1441 vector<docstring> labels;
1442 it->getLabelList(buffer_, labels);
1443 if (find(labels.begin(), labels.end(), label) != labels.end()) {
1445 processUpdateFlags(Update::FitCursor);
1452 TextMetrics const & BufferView::textMetrics(Text const * t) const
1454 return const_cast<BufferView *>(this)->textMetrics(t);
1458 TextMetrics & BufferView::textMetrics(Text const * t)
1460 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
1461 if (tmc_it == d->text_metrics_.end()) {
1462 tmc_it = d->text_metrics_.insert(
1463 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1465 return tmc_it->second;
1469 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1472 return textMetrics(t).parMetrics(pit);
1476 int BufferView::workHeight() const
1482 void BufferView::setCursor(DocIterator const & dit)
1484 size_t const n = dit.depth();
1485 for (size_t i = 0; i < n; ++i)
1486 dit[i].inset().edit(d->cursor_, true);
1488 d->cursor_.setCursor(dit);
1489 d->cursor_.selection() = false;
1493 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1495 // Would be wrong to delete anything if we have a selection.
1496 if (cur.selection())
1499 bool need_anchor_change = false;
1500 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1501 need_anchor_change);
1503 if (need_anchor_change)
1509 updateLabels(buffer_);
1517 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1519 BOOST_ASSERT(&cur.bv() == this);
1522 // this event will clear selection so we save selection for
1523 // persistent selection
1524 cap::saveSelection(cursor());
1526 // Has the cursor just left the inset?
1527 bool badcursor = false;
1528 bool leftinset = (&d->cursor_.inset() != &cur.inset());
1530 badcursor = notifyCursorLeaves(d->cursor_, cur);
1532 // FIXME: shift-mouse selection doesn't work well across insets.
1533 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1535 // do the dEPM magic if needed
1536 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1537 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1538 // the leftinset bool would not be necessary (badcursor instead).
1539 bool update = leftinset;
1540 if (!do_selection && !badcursor && d->cursor_.inTexted())
1541 update |= checkDepm(cur, d->cursor_);
1543 // if the cursor was in an empty script inset and the new
1544 // position is in the nucleus of the inset, notifyCursorLeaves
1545 // will kill the script inset itself. So we check all the
1546 // elements of the cursor to make sure that they are correct.
1547 // For an example, see bug 2933:
1548 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1549 // The code below could maybe be moved to a DocIterator method.
1550 //lyxerr << "cur before " << cur <<endl;
1551 DocIterator dit(cur.inset());
1552 dit.push_back(cur.bottom());
1554 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1555 dit.push_back(cur[i]);
1558 //lyxerr << "5 cur after" << dit <<endl;
1560 d->cursor_.setCursor(dit);
1561 d->cursor_.boundary(cur.boundary());
1563 d->cursor_.setSelection();
1565 d->cursor_.clearSelection();
1567 d->cursor_.finishUndo();
1568 d->cursor_.setCurrentFont();
1573 void BufferView::putSelectionAt(DocIterator const & cur,
1574 int length, bool backwards)
1576 d->cursor_.clearSelection();
1582 d->cursor_.pos() += length;
1583 d->cursor_.setSelection(d->cursor_, -length);
1585 d->cursor_.setSelection(d->cursor_, length);
1590 Cursor & BufferView::cursor()
1596 Cursor const & BufferView::cursor() const
1602 pit_type BufferView::anchor_ref() const
1604 return d->anchor_ref_;
1608 bool BufferView::singleParUpdate()
1610 Text & buftext = buffer_.text();
1611 pit_type const bottom_pit = d->cursor_.bottom().pit();
1612 TextMetrics & tm = textMetrics(&buftext);
1613 int old_height = tm.parMetrics(bottom_pit).height();
1615 // In Single Paragraph mode, rebreak only
1616 // the (main text, not inset!) paragraph containing the cursor.
1617 // (if this paragraph contains insets etc., rebreaking will
1618 // recursively descend)
1619 tm.redoParagraph(bottom_pit);
1620 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
1621 if (pm.height() != old_height)
1622 // Paragraph height has changed so we cannot proceed to
1623 // the singlePar optimisation.
1626 d->update_strategy_ = SingleParUpdate;
1628 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
1629 << " y2: " << pm.position() + pm.descent()
1630 << " pit: " << bottom_pit
1631 << " singlepar: 1");
1636 void BufferView::updateMetrics()
1638 Text & buftext = buffer_.text();
1639 pit_type const npit = int(buftext.paragraphs().size());
1641 if (d->anchor_ref_ > int(npit - 1)) {
1642 d->anchor_ref_ = int(npit - 1);
1646 // Clear out the position cache in case of full screen redraw,
1647 d->coord_cache_.clear();
1649 // Clear out paragraph metrics to avoid having invalid metrics
1650 // in the cache from paragraphs not relayouted below
1651 // The complete text metrics will be redone.
1652 d->text_metrics_.clear();
1654 TextMetrics & tm = textMetrics(&buftext);
1656 pit_type const pit = d->anchor_ref_;
1660 // Rebreak anchor paragraph.
1661 tm.redoParagraph(pit);
1663 // Take care of anchor offset if case a recentering is needed.
1666 int y0 = tm.parMetrics(pit).ascent() - d->offset_ref_;
1668 // Redo paragraphs above anchor if necessary.
1670 while (y1 > 0 && pit1 > 0) {
1671 y1 -= tm.parMetrics(pit1).ascent();
1673 tm.redoParagraph(pit1);
1674 y1 -= tm.parMetrics(pit1).descent();
1677 // Take care of ascent of first line
1678 y1 -= tm.parMetrics(pit1).ascent();
1680 // Normalize anchor for next time
1681 d->anchor_ref_ = pit1;
1682 d->offset_ref_ = -y1;
1684 // Grey at the beginning is ugly
1685 if (pit1 == 0 && y1 > 0) {
1691 // Redo paragraphs below the anchor if necessary.
1693 while (y2 < height_ && pit2 < int(npit) - 1) {
1694 y2 += tm.parMetrics(pit2).descent();
1696 tm.redoParagraph(pit2);
1697 y2 += tm.parMetrics(pit2).ascent();
1700 // Take care of descent of last line
1701 y2 += tm.parMetrics(pit2).descent();
1703 LYXERR(Debug::PAINTING, "\n y1: " << y1
1705 << " pit1: " << pit1
1706 << " pit2: " << pit2
1707 << " npit: " << npit
1708 << " singlepar: 0");
1710 d->update_strategy_ = FullScreenUpdate;
1714 if (lyxerr.debugging(Debug::WORKAREA)) {
1715 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
1716 d->coord_cache_.dump();
1721 void BufferView::insertLyXFile(FileName const & fname)
1723 BOOST_ASSERT(d->cursor_.inTexted());
1725 // Get absolute path of file and add ".lyx"
1726 // to the filename if necessary
1727 FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
1729 docstring const disp_fn = makeDisplayPath(filename.absFilename());
1730 // emit message signal.
1731 message(bformat(_("Inserting document %1$s..."), disp_fn));
1734 Buffer buf("", false);
1735 if (buf.loadLyXFile(filename)) {
1736 ErrorList & el = buffer_.errorList("Parse");
1737 // Copy the inserted document error list into the current buffer one.
1738 el = buf.errorList("Parse");
1739 buffer_.undo().recordUndo(d->cursor_);
1740 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
1741 buf.params().getTextClassPtr(), el);
1742 res = _("Document %1$s inserted.");
1744 res = _("Could not insert document %1$s");
1749 // emit message signal.
1750 message(bformat(res, disp_fn));
1751 buffer_.errors("Parse");
1755 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1761 // Addup contribution of nested insets, from inside to outside,
1762 // keeping the outer paragraph for a special handling below
1763 for (size_t i = dit.depth() - 1; i >= 1; --i) {
1764 CursorSlice const & sl = dit[i];
1768 // get relative position inside sl.inset()
1769 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
1771 // Make relative position inside of the edited inset relative to sl.inset()
1775 // In case of an RTL inset, the edited inset will be positioned to the left
1778 bool boundary_i = boundary && i + 1 == dit.depth();
1779 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
1784 // remember width for the case that sl.inset() is positioned in an RTL inset
1785 if (i && dit[i - 1].text()) {
1786 // If this Inset is inside a Text Inset, retrieve the Dimension
1787 // from the containing text instead of using Inset::dimension() which
1788 // might not be implemented.
1789 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
1790 // elimination of Inset::dim_ cache. This coordOffset() method needs
1791 // to be rewritten in light of the new design.
1792 Dimension const & dim = parMetrics(dit[i - 1].text(),
1793 dit[i - 1].pit()).insetDimension(&sl.inset());
1796 Dimension const dim = sl.inset().dimension(*this);
1800 //lyxerr << "Cursor::getPos, i: "
1801 // << i << " x: " << xx << " y: " << y << endl;
1804 // Add contribution of initial rows of outermost paragraph
1805 CursorSlice const & sl = dit[0];
1806 TextMetrics const & tm = textMetrics(sl.text());
1807 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
1808 BOOST_ASSERT(!pm.rows().empty());
1809 y -= pm.rows()[0].ascent();
1811 // FIXME: document this mess
1813 if (sl.pos() > 0 && dit.depth() == 1) {
1815 if (pos && boundary)
1817 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
1818 rend = pm.pos2row(pos);
1820 rend = pm.pos2row(sl.pos());
1822 size_t rend = pm.pos2row(sl.pos());
1824 for (size_t rit = 0; rit != rend; ++rit)
1825 y += pm.rows()[rit].height();
1826 y += pm.rows()[rend].ascent();
1828 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
1830 // Make relative position from the nested inset now bufferview absolute.
1831 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
1834 // In the RTL case place the nested inset at the left of the cursor in
1835 // the outer paragraph
1836 bool boundary_1 = boundary && 1 == dit.depth();
1837 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
1845 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
1847 CursorSlice const & bot = dit.bottom();
1848 TextMetrics const & tm = textMetrics(bot.text());
1849 if (!tm.has(bot.pit()))
1850 return Point(-1, -1);
1852 Point p = coordOffset(dit, boundary); // offset from outer paragraph
1853 p.y_ += tm.parMetrics(bot.pit()).position();
1858 void BufferView::draw(frontend::Painter & pain)
1860 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
1861 Text & text = buffer_.text();
1862 TextMetrics const & tm = d->text_metrics_[&text];
1863 int const y = - d->offset_ref_ + tm.parMetrics(d->anchor_ref_).ascent();
1864 PainterInfo pi(this, pain);
1866 switch (d->update_strategy_) {
1868 case NoScreenUpdate:
1869 // If no screen painting is actually needed, only some the different
1870 // coordinates of insets and paragraphs needs to be updated.
1871 pi.full_repaint = true;
1872 pi.pain.setDrawingEnabled(false);
1876 case SingleParUpdate:
1877 pi.full_repaint = false;
1878 // In general, only the current row of the outermost paragraph
1879 // will be redrawn. Particular cases where selection spans
1880 // multiple paragraph are correctly detected in TextMetrics.
1884 case DecorationUpdate:
1885 // FIXME: We should also distinguish DecorationUpdate to avoid text
1886 // drawing if possible. This is not possible to do easily right now
1887 // because of the single backing pixmap.
1889 case FullScreenUpdate:
1890 // The whole screen, including insets, will be refreshed.
1891 pi.full_repaint = true;
1893 // Clear background.
1894 pain.fillRectangle(0, 0, width_, height_,
1895 buffer_.inset().backgroundColor());
1898 // and possibly grey out below
1899 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1900 int const y2 = lastpm.second->position() + lastpm.second->descent();
1902 pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
1906 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
1910 void BufferView::message(docstring const & msg)
1913 d->gui_->message(msg);
1917 void BufferView::showDialog(string const & name)
1920 d->gui_->showDialog(name, string());
1924 void BufferView::showDialog(string const & name,
1925 string const & data, Inset * inset)
1928 d->gui_->showDialog(name, data, inset);
1932 void BufferView::updateDialog(string const & name, string const & data)
1935 d->gui_->updateDialog(name, data);
1939 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
1945 // FIXME: Move this out of BufferView again
1946 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
1948 if (!fname.isReadableFile()) {
1949 docstring const error = from_ascii(strerror(errno));
1950 docstring const file = makeDisplayPath(fname.absFilename(), 50);
1951 docstring const text =
1952 bformat(_("Could not read the specified document\n"
1953 "%1$s\ndue to the error: %2$s"), file, error);
1954 Alert::error(_("Could not read file"), text);
1958 if (!fname.isReadableFile()) {
1959 docstring const file = makeDisplayPath(fname.absFilename(), 50);
1960 docstring const text =
1961 bformat(_("%1$s\n is not readable."), file);
1962 Alert::error(_("Could not open file"), text);
1966 // FIXME UNICODE: We don't know the encoding of the file
1967 docstring file_content = fname.fileContents("UTF-8");
1968 if (file_content.empty()) {
1969 Alert::error(_("Reading not UTF-8 encoded file"),
1970 _("The file is not UTF-8 encoded.\n"
1971 "It will be read as local 8Bit-encoded.\n"
1972 "If this does not give the correct result\n"
1973 "then please change the encoding of the file\n"
1974 "to UTF-8 with a program other than LyX.\n"));
1975 file_content = fname.fileContents("local8bit");
1978 return normalize_c(file_content);
1982 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
1984 docstring const tmpstr = contentsOfPlaintextFile(f);
1989 Cursor & cur = cursor();
1990 cap::replaceSelection(cur);
1991 buffer_.undo().recordUndo(cur);
1993 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
1995 cur.innerText()->insertStringAsLines(cur, tmpstr);