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"
86 using std::istringstream;
87 using std::istream_iterator;
91 using std::mem_fun_ref;
97 using support::addPath;
98 using support::bformat;
99 using support::FileFilterList;
100 using support::FileName;
101 using support::fileSearch;
102 using support::makeDisplayPath;
103 using support::makeAbsPath;
104 using support::package;
106 namespace Alert = frontend::Alert;
110 /// Return an inset of this class if it exists at the current cursor position
112 T * getInsetByCode(Cursor const & cur, InsetCode code)
114 DocIterator it = cur;
115 Inset * inset = it.nextInset();
116 if (inset && inset->lyxCode() == code)
117 return static_cast<T*>(inset);
122 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
125 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
126 docstring const & contents)
128 DocIterator tmpdit = dit;
131 Inset const * inset = tmpdit.nextInset();
133 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
134 && (contents.empty() ||
135 static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
139 tmpdit.forwardInset();
146 /// Looks for next inset with one of the given codes.
147 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
151 DocIterator tmpdit = dit;
152 tmpdit.forwardInset();
157 Inset const * inset = tmpdit.nextInset();
159 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
160 contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
164 if (!findNextInset(tmpdit, codes, contents)) {
165 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
166 tmpdit = doc_iterator_begin(tmpdit.bottom().inset());
167 if (!findNextInset(tmpdit, codes, contents))
178 /// Looks for next inset with the given code
179 void findInset(DocIterator & dit, InsetCode code, bool same_content)
181 findInset(dit, vector<InsetCode>(1, code), same_content);
185 /// Moves cursor to the next inset with one of the given codes.
186 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
189 Cursor tmpcur = bv->cursor();
190 if (!findInset(tmpcur, codes, same_content)) {
191 bv->cursor().message(_("No more insets"));
195 tmpcur.clearSelection();
196 bv->setCursor(tmpcur);
200 /// Moves cursor to the next inset with given code.
201 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
203 gotoInset(bv, vector<InsetCode>(1, code), same_content);
207 /// A map from a Text to the associated text metrics
208 typedef std::map<Text const *, TextMetrics> TextMetricsCache;
210 enum ScreenUpdateStrategy {
220 /////////////////////////////////////////////////////////////////////
224 /////////////////////////////////////////////////////////////////////
226 struct BufferView::Private
228 Private(BufferView & bv): wh_(0), cursor_(bv),
229 anchor_ref_(0), offset_ref_(0), need_centering_(false),
230 last_inset_(0), gui_(0)
234 ScrollbarParameters scrollbarParameters_;
236 ScreenUpdateStrategy update_strategy_;
238 CoordCache coord_cache_;
240 /// Estimated average par height for scrollbar.
242 /// this is used to handle XSelection events in the right manner.
251 pit_type anchor_ref_;
255 bool need_centering_;
257 /// keyboard mapping object.
260 /// last visited inset.
261 /** kept to send setMouseHover(false).
262 * Not owned, so don't delete.
266 mutable TextMetricsCache text_metrics_;
269 /** Not owned, so don't delete.
271 frontend::GuiBufferViewDelegate * gui_;
275 BufferView::BufferView(Buffer & buf)
276 : width_(0), height_(0), buffer_(buf), d(new Private(*this))
278 d->xsel_cache_.set = false;
279 d->intl_.initKeyMapper(lyxrc.use_kbmap);
281 d->cursor_.push(buffer_.inset());
282 d->cursor_.resetAnchor();
283 d->cursor_.setCurrentFont();
285 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
286 graphics::Previews::get().generateBufferPreviews(buffer_);
290 BufferView::~BufferView()
292 // current buffer is going to be switched-off, save cursor pos
293 // Ideally, the whole cursor stack should be saved, but session
294 // currently can only handle bottom (whole document) level pit and pos.
295 // That is to say, if a cursor is in a nested inset, it will be
296 // restore to the left of the top level inset.
297 LastFilePosSection::FilePos fp;
298 fp.pit = d->cursor_.bottom().pit();
299 fp.pos = d->cursor_.bottom().pos();
300 LyX::ref().session().lastFilePos().save(buffer_.fileName(), fp);
306 Intl & BufferView::getIntl()
312 Intl const & BufferView::getIntl() const
318 CoordCache & BufferView::coordCache()
320 return d->coord_cache_;
324 CoordCache const & BufferView::coordCache() const
326 return d->coord_cache_;
330 Buffer & BufferView::buffer()
336 Buffer const & BufferView::buffer() const
342 bool BufferView::fitCursor()
344 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
345 frontend::FontMetrics const & fm =
346 theFontMetrics(d->cursor_.getFont().fontInfo());
347 int const asc = fm.maxAscent();
348 int const des = fm.maxDescent();
349 Point const p = getPos(d->cursor_, d->cursor_.boundary());
350 if (p.y_ - asc >= 0 && p.y_ + des < height_)
358 void BufferView::processUpdateFlags(Update::flags flags)
360 // last_inset_ points to the last visited inset. This pointer may become
361 // invalid because of keyboard editing. Since all such operations
362 // causes screen update(), I reset last_inset_ to avoid such a problem.
364 // This is close to a hot-path.
365 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
366 << "[fitcursor = " << (flags & Update::FitCursor)
367 << ", forceupdate = " << (flags & Update::Force)
368 << ", singlepar = " << (flags & Update::SinglePar)
369 << "] buffer: " << &buffer_);
371 // Update macro store
372 if (!(cursor().inMathed() && cursor().inMacroMode()))
373 buffer_.updateMacros();
375 // Now do the first drawing step if needed. This consists on updating
376 // the CoordCache in updateMetrics().
377 // The second drawing step is done in WorkArea::redraw() if needed.
379 // Case when no explicit update is requested.
381 // no need to redraw anything.
382 d->update_strategy_ = NoScreenUpdate;
386 if (flags == Update::Decoration) {
387 d->update_strategy_ = DecorationUpdate;
392 if (flags == Update::FitCursor
393 || flags == (Update::Decoration | Update::FitCursor)) {
394 bool const fit_cursor = fitCursor();
395 // tell the frontend to update the screen if needed.
401 if (flags & Update::Decoration) {
402 d->update_strategy_ = DecorationUpdate;
406 // no screen update is needed.
407 d->update_strategy_ = NoScreenUpdate;
411 bool const full_metrics = flags & Update::Force;
413 if (full_metrics || !singleParUpdate())
414 // We have to update the full screen metrics.
417 if (!(flags & Update::FitCursor)) {
422 //FIXME: updateMetrics() does not update paragraph position
423 // This is done at draw() time. So we need a redraw!
426 // The screen has already been updated thanks to the
427 // 'buffer_.changed()' call three line above. So no need
431 // The screen has been recentered around the cursor position so
438 void BufferView::updateScrollbar()
440 Text & t = buffer_.text();
441 TextMetrics & tm = d->text_metrics_[&t];
443 int const parsize = int(t.paragraphs().size() - 1);
444 if (d->anchor_ref_ > parsize) {
445 d->anchor_ref_ = parsize;
449 LYXERR(Debug::GUI, " Updating scrollbar: height: "
450 << t.paragraphs().size()
451 << " curr par: " << d->cursor_.bottom().pit()
452 << " default height " << defaultRowHeight());
454 // It would be better to fix the scrollbar to understand
455 // values in [0..1] and divide everything by wh
457 // estimated average paragraph height:
459 d->wh_ = height_ / 4;
461 int h = tm.parMetrics(d->anchor_ref_).height();
463 // Normalize anchor/offset (MV):
464 while (d->offset_ref_ > h && d->anchor_ref_ < parsize) {
467 h = tm.parMetrics(d->anchor_ref_).height();
469 // Look at paragraph heights on-screen
472 for (pit_type pit = d->anchor_ref_; pit <= parsize; ++pit) {
475 int const h2 = tm.parMetrics(pit).height();
481 int const hav = sumh / nh;
482 // More realistic average paragraph height
487 d->scrollbarParameters_.height = (parsize + 1) * d->wh_;
488 d->scrollbarParameters_.position = d->anchor_ref_ * d->wh_ + int(d->offset_ref_ * d->wh_ / float(h));
489 d->scrollbarParameters_.lineScrollHeight = int(d->wh_ * defaultRowHeight() / float(h));
493 ScrollbarParameters const & BufferView::scrollbarParameters() const
495 return d->scrollbarParameters_;
499 void BufferView::scrollDocView(int value)
501 LYXERR(Debug::GUI, "[ value = " << value << "]");
503 Text & t = buffer_.text();
504 TextMetrics & tm = d->text_metrics_[&t];
506 float const bar = value / float(d->wh_ * t.paragraphs().size());
508 d->anchor_ref_ = int(bar * t.paragraphs().size());
509 if (d->anchor_ref_ > int(t.paragraphs().size()) - 1)
510 d->anchor_ref_ = int(t.paragraphs().size()) - 1;
512 tm.redoParagraph(d->anchor_ref_);
513 int const h = tm.parMetrics(d->anchor_ref_).height();
514 d->offset_ref_ = int((bar * t.paragraphs().size() - d->anchor_ref_) * h);
520 void BufferView::setCursorFromScrollbar()
522 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
524 int const height = 2 * defaultRowHeight();
525 int const first = height;
526 int const last = height_ - height;
527 Cursor & cur = d->cursor_;
529 switch (cursorStatus(cur)) {
531 // We reset the cursor because cursorStatus() does not
532 // work when the cursor is within mathed.
533 cur.reset(buffer_.inset());
534 tm.setCursorFromCoordinates(cur, 0, first);
535 cur.clearSelection();
538 // We reset the cursor because cursorStatus() does not
539 // work when the cursor is within mathed.
540 cur.reset(buffer_.inset());
541 tm.setCursorFromCoordinates(cur, 0, last);
542 cur.clearSelection();
545 int const y = getPos(cur, cur.boundary()).y_;
546 int const newy = min(last, max(y, first));
548 cur.reset(buffer_.inset());
549 tm.setCursorFromCoordinates(cur, 0, newy);
555 Change const BufferView::getCurrentChange() const
557 if (!d->cursor_.selection())
558 return Change(Change::UNCHANGED);
560 DocIterator dit = d->cursor_.selectionBegin();
561 return dit.paragraph().lookupChange(dit.pos());
565 // this could be used elsewhere as well?
566 // FIXME: This does not work within mathed!
567 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
569 Point const p = getPos(dit, dit.boundary());
572 if (p.y_ > workHeight())
578 void BufferView::saveBookmark(unsigned int idx)
580 // tenatively save bookmark, id and pos will be used to
581 // acturately locate a bookmark in a 'live' lyx session.
582 // pit and pos will be updated with bottom level pit/pos
584 LyX::ref().session().bookmarks().save(
586 d->cursor_.bottom().pit(),
587 d->cursor_.bottom().pos(),
588 d->cursor_.paragraph().id(),
593 // emit message signal.
594 message(_("Save bookmark"));
598 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
599 int top_id, pos_type top_pos)
601 bool success = false;
604 d->cursor_.clearSelection();
606 // if a valid par_id is given, try it first
607 // This is the case for a 'live' bookmark when unique paragraph ID
608 // is used to track bookmarks.
610 ParIterator par = buffer_.getParFromID(top_id);
611 if (par != buffer_.par_iterator_end()) {
612 doc_it = makeDocIterator(par, min(par->size(), top_pos));
613 // Some slices of the iterator may not be
614 // reachable (e.g. closed collapsable inset)
615 // so the dociterator may need to be
616 // shortened. Otherwise, setCursor may crash
617 // lyx when the cursor can not be set to these
619 size_t const n = doc_it.depth();
620 for (size_t i = 0; i < n; ++i)
621 if (doc_it[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
629 // if top_id == 0, or searching through top_id failed
630 // This is the case for a 'restored' bookmark when only bottom
631 // (document level) pit was saved. Because of this, bookmark
632 // restoration is inaccurate. If a bookmark was within an inset,
633 // it will be restored to the left of the outmost inset that contains
635 if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
636 doc_it = doc_iterator_begin(buffer_.inset());
637 doc_it.pit() = bottom_pit;
638 doc_it.pos() = min(bottom_pos, doc_it.paragraph().size());
643 // Note: only bottom (document) level pit is set.
645 // set the current font.
646 d->cursor_.setCurrentFont();
647 // To center the screen on this new position we need the
648 // paragraph position which is computed at draw() time.
649 // So we need a redraw!
652 // We need another redraw because of the screen recentering.
660 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
662 if (lyxrc.rtl_support) {
663 if (d->cursor_.real_current_font.isRightToLeft()) {
664 if (d->intl_.keymap == Intl::PRIMARY)
665 d->intl_.keyMapSec();
667 if (d->intl_.keymap == Intl::SECONDARY)
668 d->intl_.keyMapPrim();
672 d->intl_.getTransManager().translateAndInsert(c, t, cur);
676 int BufferView::workWidth() const
682 void BufferView::updateOffsetRef()
684 // No need to update d->offset_ref_ in this case.
685 if (!d->need_centering_)
688 // We are not properly started yet, delay until resizing is
693 CursorSlice & bot = d->cursor_.bottom();
694 TextMetrics & tm = d->text_metrics_[bot.text()];
695 ParagraphMetrics const & pm = tm.parMetrics(bot.pit());
696 int y = coordOffset(d->cursor_, d->cursor_.boundary()).y_;
697 d->offset_ref_ = y + pm.ascent() - height_ / 2;
699 d->need_centering_ = false;
703 void BufferView::center()
705 d->anchor_ref_ = d->cursor_.bottom().pit();
706 d->need_centering_ = true;
710 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
714 Cursor & cur = d->cursor_;
716 switch (cmd.action) {
719 flag.enabled(buffer_.undo().hasUndoStack());
722 flag.enabled(buffer_.undo().hasRedoStack());
724 case LFUN_FILE_INSERT:
725 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
726 case LFUN_FILE_INSERT_PLAINTEXT:
727 case LFUN_BOOKMARK_SAVE:
728 // FIXME: Actually, these LFUNS should be moved to Text
729 flag.enabled(cur.inTexted());
731 case LFUN_FONT_STATE:
732 case LFUN_LABEL_INSERT:
733 case LFUN_INFO_INSERT:
734 case LFUN_PARAGRAPH_GOTO:
736 case LFUN_REFERENCE_NEXT:
738 case LFUN_WORD_REPLACE:
741 case LFUN_MARK_TOGGLE:
742 case LFUN_SCREEN_RECENTER:
743 case LFUN_BIBTEX_DATABASE_ADD:
744 case LFUN_BIBTEX_DATABASE_DEL:
745 case LFUN_WORDS_COUNT:
746 case LFUN_NEXT_INSET_TOGGLE:
750 case LFUN_LABEL_GOTO: {
751 flag.enabled(!cmd.argument().empty()
752 || getInsetByCode<InsetRef>(cur, REF_CODE));
756 case LFUN_CHANGES_TRACK:
758 flag.setOnOff(buffer_.params().trackChanges);
761 case LFUN_CHANGES_OUTPUT:
763 flag.setOnOff(buffer_.params().outputChanges);
766 case LFUN_CHANGES_MERGE:
767 case LFUN_CHANGE_NEXT:
768 case LFUN_ALL_CHANGES_ACCEPT:
769 case LFUN_ALL_CHANGES_REJECT:
770 // TODO: context-sensitive enabling of LFUNs
771 // In principle, these command should only be enabled if there
772 // is a change in the document. However, without proper
773 // optimizations, this will inevitably result in poor performance.
777 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
778 flag.setOnOff(buffer_.params().compressed);
782 case LFUN_BUFFER_TOGGLE_EMBEDDING: {
783 flag.setOnOff(buffer_.params().embedded);
788 case LFUN_SCREEN_DOWN:
792 // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
793 // everywhere else before this can enabled:
794 case LFUN_SCREEN_UP_SELECT:
795 case LFUN_SCREEN_DOWN_SELECT:
799 case LFUN_LAYOUT_TABULAR:
800 flag.enabled(cur.innerInsetOfType(TABULAR_CODE));
804 case LFUN_LAYOUT_PARAGRAPH:
805 flag.enabled(cur.inset().forceDefaultParagraphs(cur.idx()));
808 case LFUN_INSET_SETTINGS: {
809 InsetCode code = cur.inset().lyxCode();
813 enable = cmd.argument() == "tabular";
816 enable = cmd.argument() == "ert";
819 enable = cmd.argument() == "float";
822 enable = cmd.argument() == "wrap";
825 enable = cmd.argument() == "note";
828 enable = cmd.argument() == "branch";
831 enable = cmd.argument() == "box";
834 enable = cmd.argument() == "listings";
839 flag.enabled(enable);
843 case LFUN_DIALOG_SHOW_NEW_INSET:
844 flag.enabled(cur.inset().lyxCode() != ERT_CODE &&
845 cur.inset().lyxCode() != LISTINGS_CODE);
846 if (cur.inset().lyxCode() == CAPTION_CODE) {
848 if (cur.inset().getStatus(cur, cmd, flag))
861 Update::flags BufferView::dispatch(FuncRequest const & cmd)
863 //lyxerr << [ cmd = " << cmd << "]" << endl;
865 // Make sure that the cached BufferView is correct.
866 LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
867 << " arg[" << to_utf8(cmd.argument()) << ']'
868 << " x[" << cmd.x << ']'
869 << " y[" << cmd.y << ']'
870 << " button[" << cmd.button() << ']');
872 Cursor & cur = d->cursor_;
873 // Default Update flags.
874 Update::flags updateFlags = Update::Force | Update::FitCursor;
876 switch (cmd.action) {
879 cur.message(_("Undo"));
880 cur.clearSelection();
881 if (!cur.textUndo()) {
882 cur.message(_("No further undo information"));
883 updateFlags = Update::None;
888 cur.message(_("Redo"));
889 cur.clearSelection();
890 if (!cur.textRedo()) {
891 cur.message(_("No further redo information"));
892 updateFlags = Update::None;
896 case LFUN_FONT_STATE:
897 cur.message(cur.currentState());
900 case LFUN_BOOKMARK_SAVE:
901 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
904 case LFUN_LABEL_GOTO: {
905 docstring label = cmd.argument();
908 getInsetByCode<InsetRef>(d->cursor_,
911 label = inset->getParam("reference");
912 // persistent=false: use temp_bookmark
922 case LFUN_PARAGRAPH_GOTO: {
923 int const id = convert<int>(to_utf8(cmd.argument()));
925 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
926 b = theBufferList().next(b)) {
928 ParIterator par = b->getParFromID(id);
929 if (par == b->par_iterator_end()) {
930 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
932 LYXERR(Debug::INFO, "Paragraph " << par->id()
933 << " found in buffer `"
934 << b->absFileName() << "'.");
938 setCursor(makeDocIterator(par, 0));
940 // Switch to other buffer view and resend cmd
941 theLyXFunc().dispatch(FuncRequest(
942 LFUN_BUFFER_SWITCH, b->absFileName()));
943 theLyXFunc().dispatch(cmd);
944 updateFlags = Update::None;
954 gotoInset(this, NOTE_CODE, false);
957 case LFUN_REFERENCE_NEXT: {
958 vector<InsetCode> tmp;
959 tmp.push_back(LABEL_CODE);
960 tmp.push_back(REF_CODE);
961 gotoInset(this, tmp, true);
965 case LFUN_CHANGES_TRACK:
966 buffer_.params().trackChanges = !buffer_.params().trackChanges;
969 case LFUN_CHANGES_OUTPUT:
970 buffer_.params().outputChanges = !buffer_.params().outputChanges;
971 if (buffer_.params().outputChanges) {
972 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
973 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
974 LaTeXFeatures::isAvailable("xcolor");
976 if (!dvipost && !xcolorsoul) {
977 Alert::warning(_("Changes not shown in LaTeX output"),
978 _("Changes will not be highlighted in LaTeX output, "
979 "because neither dvipost nor xcolor/soul are installed.\n"
980 "Please install these packages or redefine "
981 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
982 } else if (!xcolorsoul) {
983 Alert::warning(_("Changes not shown in LaTeX output"),
984 _("Changes will not be highlighted in LaTeX output "
985 "when using pdflatex, because xcolor and soul are not installed.\n"
986 "Please install both packages or redefine "
987 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
992 case LFUN_CHANGE_NEXT:
993 findNextChange(this);
996 case LFUN_CHANGES_MERGE:
997 if (findNextChange(this))
998 showDialog("changes");
1001 case LFUN_ALL_CHANGES_ACCEPT:
1002 // select complete document
1003 d->cursor_.reset(buffer_.inset());
1004 d->cursor_.selHandle(true);
1005 buffer_.text().cursorBottom(d->cursor_);
1006 // accept everything in a single step to support atomic undo
1007 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1010 case LFUN_ALL_CHANGES_REJECT:
1011 // select complete document
1012 d->cursor_.reset(buffer_.inset());
1013 d->cursor_.selHandle(true);
1014 buffer_.text().cursorBottom(d->cursor_);
1015 // reject everything in a single step to support atomic undo
1016 // Note: reject does not work recursively; the user may have to repeat the operation
1017 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1020 case LFUN_WORD_FIND:
1024 case LFUN_WORD_REPLACE: {
1025 bool has_deleted = false;
1026 if (cur.selection()) {
1027 DocIterator beg = cur.selectionBegin();
1028 DocIterator end = cur.selectionEnd();
1029 if (beg.pit() == end.pit()) {
1030 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1031 if (cur.paragraph().isDeleted(p))
1036 replace(this, cmd, has_deleted);
1041 cur.clearSelection();
1043 cur.message(from_utf8(N_("Mark off")));
1047 cur.clearSelection();
1050 cur.message(from_utf8(N_("Mark on")));
1053 case LFUN_MARK_TOGGLE:
1054 cur.clearSelection();
1057 cur.message(from_utf8(N_("Mark removed")));
1060 cur.message(from_utf8(N_("Mark set")));
1065 case LFUN_SCREEN_RECENTER:
1069 case LFUN_BIBTEX_DATABASE_ADD: {
1070 Cursor tmpcur = d->cursor_;
1071 findInset(tmpcur, BIBTEX_CODE, false);
1072 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1075 if (inset->addDatabase(to_utf8(cmd.argument())))
1076 buffer_.updateBibfilesCache();
1081 case LFUN_BIBTEX_DATABASE_DEL: {
1082 Cursor tmpcur = d->cursor_;
1083 findInset(tmpcur, BIBTEX_CODE, false);
1084 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1087 if (inset->delDatabase(to_utf8(cmd.argument())))
1088 buffer_.updateBibfilesCache();
1093 case LFUN_WORDS_COUNT: {
1094 DocIterator from, to;
1095 if (cur.selection()) {
1096 from = cur.selectionBegin();
1097 to = cur.selectionEnd();
1099 from = doc_iterator_begin(buffer_.inset());
1100 to = doc_iterator_end(buffer_.inset());
1102 int const count = countWords(from, to);
1105 if (cur.selection())
1106 message = bformat(_("%1$d words in selection."),
1109 message = bformat(_("%1$d words in document."),
1113 if (cur.selection())
1114 message = _("One word in selection.");
1116 message = _("One word in document.");
1119 Alert::information(_("Count words"), message);
1123 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1124 // turn compression on/off
1125 buffer_.params().compressed = !buffer_.params().compressed;
1128 case LFUN_BUFFER_TOGGLE_EMBEDDING:
1129 // turn embedding on/off
1130 buffer_.embeddedFiles().enable(!buffer_.params().embedded);
1133 case LFUN_NEXT_INSET_TOGGLE: {
1134 // this is the real function we want to invoke
1135 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1136 // if there is an inset at cursor, see whether it
1138 Inset * inset = cur.nextInset();
1140 if (inset->isActive()) {
1141 Cursor tmpcur = cur;
1142 tmpcur.pushBackward(*inset);
1143 inset->dispatch(tmpcur, tmpcmd);
1144 if (tmpcur.result().dispatched()) {
1147 } else if (inset->editable() == Inset::IS_EDITABLE) {
1148 inset->edit(cur, true);
1151 // if it did not work, try the underlying inset.
1152 if (!cur.result().dispatched())
1153 cur.dispatch(tmpcmd);
1155 if (cur.result().dispatched())
1156 cur.clearSelection();
1161 case LFUN_SCREEN_UP:
1162 case LFUN_SCREEN_DOWN: {
1163 Point p = getPos(cur, cur.boundary());
1164 if (p.y_ < 0 || p.y_ > height_) {
1165 // The cursor is off-screen so recenter before proceeding.
1168 //FIXME: updateMetrics() does not update paragraph position
1169 // This is done at draw() time. So we need a redraw!
1170 // But no screen update is needed.
1171 d->update_strategy_ = NoScreenUpdate;
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()?
1180 // The metrics are already up to date. see scroll()
1181 updateFlags = Update::None;
1185 case LFUN_SCREEN_UP_SELECT:
1186 case LFUN_SCREEN_DOWN_SELECT: {
1187 cur.selHandle(true);
1188 size_t initial_depth = cur.depth();
1189 Point const p = getPos(cur, cur.boundary());
1190 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1191 // FIXME: We need to verify if the cursor stayed within an inset...
1192 //cur.reset(buffer_.inset());
1193 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1195 while (cur.depth() > initial_depth) {
1198 // FIXME: we need to do a redraw again because of the selection
1199 // But no screen update is needed.
1200 d->update_strategy_ = NoScreenUpdate;
1202 updateFlags = Update::Force | Update::FitCursor;
1207 updateFlags = Update::None;
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
1260 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1262 TextMetrics & tm = d->text_metrics_[&text];
1263 Inset * inset = tm.checkInsetHit(x, y);
1267 if (!inset->descendable())
1268 // No need to go further down if the inset is not
1272 size_t cell_number = inset->nargs();
1273 // Check all the inner cell.
1274 for (size_t i = 0; i != cell_number; ++i) {
1275 Text const * inner_text = inset->getText(i);
1278 Inset const * inset_deeper =
1279 getCoveringInset(*inner_text, x, y);
1281 return inset_deeper;
1289 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1291 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1293 // This is only called for mouse related events including
1294 // LFUN_FILE_OPEN generated by drag-and-drop.
1295 FuncRequest cmd = cmd0;
1298 cur.push(buffer_.inset());
1299 cur.selection() = d->cursor_.selection();
1301 // Either the inset under the cursor or the
1302 // surrounding Text will handle this event.
1304 // make sure we stay within the screen...
1305 cmd.y = min(max(cmd.y, -1), height_);
1307 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1309 // Get inset under mouse, if there is one.
1310 Inset const * covering_inset =
1311 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1312 if (covering_inset == d->last_inset_)
1313 // Same inset, no need to do anything...
1316 bool need_redraw = false;
1317 // const_cast because of setMouseHover().
1318 Inset * inset = const_cast<Inset *>(covering_inset);
1320 // Remove the hint on the last hovered inset (if any).
1321 need_redraw |= d->last_inset_->setMouseHover(false);
1323 // Highlighted the newly hovered inset (if any).
1324 need_redraw |= inset->setMouseHover(true);
1325 d->last_inset_ = inset;
1329 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1330 << cmd.x << ", " << cmd.y << ")");
1332 d->update_strategy_ = DecorationUpdate;
1334 // This event (moving without mouse click) is not passed further.
1335 // This should be changed if it is further utilized.
1340 // Build temporary cursor.
1341 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1343 // Put anchor at the same position.
1346 // Try to dispatch to an non-editable inset near this position
1347 // via the temp cursor. If the inset wishes to change the real
1348 // cursor it has to do so explicitly by using
1349 // cur.bv().cursor() = cur; (or similar)
1351 inset->dispatch(cur, cmd);
1353 // Now dispatch to the temporary cursor. If the real cursor should
1354 // be modified, the inset's dispatch has to do so explicitly.
1355 if (!cur.result().dispatched())
1358 //Do we have a selection?
1359 theSelection().haveSelection(cursor().selection());
1361 // If the command has been dispatched,
1362 if (cur.result().dispatched()
1363 // an update is asked,
1364 && cur.result().update())
1365 processUpdateFlags(cur.result().update());
1369 void BufferView::scroll(int y)
1378 void BufferView::scrollDown(int offset)
1380 Text * text = &buffer_.text();
1381 TextMetrics & tm = d->text_metrics_[text];
1382 int ymax = height_ + offset;
1384 std::pair<pit_type, ParagraphMetrics const *> last = tm.last();
1385 int bottom_pos = last.second->position() + last.second->descent();
1386 if (last.first + 1 == int(text->paragraphs().size())) {
1387 if (bottom_pos <= height_)
1389 offset = min(offset, bottom_pos - height_);
1392 if (bottom_pos > ymax)
1394 tm.newParMetricsDown();
1396 d->offset_ref_ += offset;
1402 void BufferView::scrollUp(int offset)
1404 Text * text = &buffer_.text();
1405 TextMetrics & tm = d->text_metrics_[text];
1406 int ymin = - offset;
1408 std::pair<pit_type, ParagraphMetrics const *> first = tm.first();
1409 int top_pos = first.second->position() - first.second->ascent();
1410 if (first.first == 0) {
1413 offset = min(offset, - top_pos);
1418 tm.newParMetricsUp();
1420 d->offset_ref_ -= offset;
1426 void BufferView::setCursorFromRow(int row)
1431 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1433 d->cursor_.reset(buffer_.inset());
1435 buffer_.text().setCursor(d->cursor_, 0, 0);
1437 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1441 void BufferView::gotoLabel(docstring const & label)
1443 for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1444 vector<docstring> labels;
1445 it->getLabelList(buffer_, labels);
1446 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1448 processUpdateFlags(Update::FitCursor);
1455 TextMetrics const & BufferView::textMetrics(Text const * t) const
1457 return const_cast<BufferView *>(this)->textMetrics(t);
1461 TextMetrics & BufferView::textMetrics(Text const * t)
1463 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
1464 if (tmc_it == d->text_metrics_.end()) {
1465 tmc_it = d->text_metrics_.insert(
1466 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1468 return tmc_it->second;
1472 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1475 return textMetrics(t).parMetrics(pit);
1479 int BufferView::workHeight() const
1485 void BufferView::setCursor(DocIterator const & dit)
1487 size_t const n = dit.depth();
1488 for (size_t i = 0; i < n; ++i)
1489 dit[i].inset().edit(d->cursor_, true);
1491 d->cursor_.setCursor(dit);
1492 d->cursor_.selection() = false;
1496 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1498 // Would be wrong to delete anything if we have a selection.
1499 if (cur.selection())
1502 bool need_anchor_change = false;
1503 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1504 need_anchor_change);
1506 if (need_anchor_change)
1512 updateLabels(buffer_);
1520 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1522 BOOST_ASSERT(&cur.bv() == this);
1525 // this event will clear selection so we save selection for
1526 // persistent selection
1527 cap::saveSelection(cursor());
1529 // Has the cursor just left the inset?
1530 bool badcursor = false;
1531 bool leftinset = (&d->cursor_.inset() != &cur.inset());
1533 badcursor = notifyCursorLeaves(d->cursor_, cur);
1535 // FIXME: shift-mouse selection doesn't work well across insets.
1536 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1538 // do the dEPM magic if needed
1539 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1540 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1541 // the leftinset bool would not be necessary (badcursor instead).
1542 bool update = leftinset;
1543 if (!do_selection && !badcursor && d->cursor_.inTexted())
1544 update |= checkDepm(cur, d->cursor_);
1546 // if the cursor was in an empty script inset and the new
1547 // position is in the nucleus of the inset, notifyCursorLeaves
1548 // will kill the script inset itself. So we check all the
1549 // elements of the cursor to make sure that they are correct.
1550 // For an example, see bug 2933:
1551 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1552 // The code below could maybe be moved to a DocIterator method.
1553 //lyxerr << "cur before " << cur <<std::endl;
1554 DocIterator dit(cur.inset());
1555 dit.push_back(cur.bottom());
1557 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1558 dit.push_back(cur[i]);
1561 //lyxerr << "5 cur after" << dit <<std::endl;
1563 d->cursor_.setCursor(dit);
1564 d->cursor_.boundary(cur.boundary());
1566 d->cursor_.setSelection();
1568 d->cursor_.clearSelection();
1570 d->cursor_.finishUndo();
1571 d->cursor_.setCurrentFont();
1576 void BufferView::putSelectionAt(DocIterator const & cur,
1577 int length, bool backwards)
1579 d->cursor_.clearSelection();
1585 d->cursor_.pos() += length;
1586 d->cursor_.setSelection(d->cursor_, -length);
1588 d->cursor_.setSelection(d->cursor_, length);
1593 Cursor & BufferView::cursor()
1599 Cursor const & BufferView::cursor() const
1605 pit_type BufferView::anchor_ref() const
1607 return d->anchor_ref_;
1611 bool BufferView::singleParUpdate()
1613 Text & buftext = buffer_.text();
1614 pit_type const bottom_pit = d->cursor_.bottom().pit();
1615 TextMetrics & tm = textMetrics(&buftext);
1616 int old_height = tm.parMetrics(bottom_pit).height();
1618 // In Single Paragraph mode, rebreak only
1619 // the (main text, not inset!) paragraph containing the cursor.
1620 // (if this paragraph contains insets etc., rebreaking will
1621 // recursively descend)
1622 tm.redoParagraph(bottom_pit);
1623 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
1624 if (pm.height() != old_height)
1625 // Paragraph height has changed so we cannot proceed to
1626 // the singlePar optimisation.
1629 d->update_strategy_ = SingleParUpdate;
1631 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
1632 << " y2: " << pm.position() + pm.descent()
1633 << " pit: " << bottom_pit
1634 << " singlepar: 1");
1639 void BufferView::updateMetrics()
1641 Text & buftext = buffer_.text();
1642 pit_type const npit = int(buftext.paragraphs().size());
1644 if (d->anchor_ref_ > int(npit - 1)) {
1645 d->anchor_ref_ = int(npit - 1);
1649 // Clear out the position cache in case of full screen redraw,
1650 d->coord_cache_.clear();
1652 // Clear out paragraph metrics to avoid having invalid metrics
1653 // in the cache from paragraphs not relayouted below
1654 // The complete text metrics will be redone.
1655 d->text_metrics_.clear();
1657 TextMetrics & tm = textMetrics(&buftext);
1659 pit_type const pit = d->anchor_ref_;
1663 // Rebreak anchor paragraph.
1664 tm.redoParagraph(pit);
1666 // Take care of anchor offset if case a recentering is needed.
1669 int y0 = tm.parMetrics(pit).ascent() - d->offset_ref_;
1671 // Redo paragraphs above anchor if necessary.
1673 while (y1 > 0 && pit1 > 0) {
1674 y1 -= tm.parMetrics(pit1).ascent();
1676 tm.redoParagraph(pit1);
1677 y1 -= tm.parMetrics(pit1).descent();
1680 // Take care of ascent of first line
1681 y1 -= tm.parMetrics(pit1).ascent();
1683 // Normalize anchor for next time
1684 d->anchor_ref_ = pit1;
1685 d->offset_ref_ = -y1;
1687 // Grey at the beginning is ugly
1688 if (pit1 == 0 && y1 > 0) {
1694 // Redo paragraphs below the anchor if necessary.
1696 while (y2 < height_ && pit2 < int(npit) - 1) {
1697 y2 += tm.parMetrics(pit2).descent();
1699 tm.redoParagraph(pit2);
1700 y2 += tm.parMetrics(pit2).ascent();
1703 // Take care of descent of last line
1704 y2 += tm.parMetrics(pit2).descent();
1706 LYXERR(Debug::PAINTING, "\n y1: " << y1
1708 << " pit1: " << pit1
1709 << " pit2: " << pit2
1710 << " npit: " << npit
1711 << " singlepar: 0");
1713 d->update_strategy_ = FullScreenUpdate;
1715 if (lyxerr.debugging(Debug::WORKAREA)) {
1716 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
1717 d->coord_cache_.dump();
1722 void BufferView::insertLyXFile(FileName const & fname)
1724 BOOST_ASSERT(d->cursor_.inTexted());
1726 // Get absolute path of file and add ".lyx"
1727 // to the filename if necessary
1728 FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
1730 docstring const disp_fn = makeDisplayPath(filename.absFilename());
1731 // emit message signal.
1732 message(bformat(_("Inserting document %1$s..."), disp_fn));
1735 Buffer buf("", false);
1736 if (buf.loadLyXFile(filename)) {
1737 ErrorList & el = buffer_.errorList("Parse");
1738 // Copy the inserted document error list into the current buffer one.
1739 el = buf.errorList("Parse");
1740 buffer_.undo().recordUndo(d->cursor_);
1741 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
1742 buf.params().getTextClassPtr(), el);
1743 res = _("Document %1$s inserted.");
1745 res = _("Could not insert document %1$s");
1750 // emit message signal.
1751 message(bformat(res, disp_fn));
1752 buffer_.errors("Parse");
1756 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1762 // Addup contribution of nested insets, from inside to outside,
1763 // keeping the outer paragraph for a special handling below
1764 for (size_t i = dit.depth() - 1; i >= 1; --i) {
1765 CursorSlice const & sl = dit[i];
1769 // get relative position inside sl.inset()
1770 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
1772 // Make relative position inside of the edited inset relative to sl.inset()
1776 // In case of an RTL inset, the edited inset will be positioned to the left
1779 bool boundary_i = boundary && i + 1 == dit.depth();
1780 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
1785 // remember width for the case that sl.inset() is positioned in an RTL inset
1786 if (i && dit[i - 1].text()) {
1787 // If this Inset is inside a Text Inset, retrieve the Dimension
1788 // from the containing text instead of using Inset::dimension() which
1789 // might not be implemented.
1790 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
1791 // elimination of Inset::dim_ cache. This coordOffset() method needs
1792 // to be rewritten in light of the new design.
1793 Dimension const & dim = parMetrics(dit[i - 1].text(),
1794 dit[i - 1].pit()).insetDimension(&sl.inset());
1797 Dimension const dim = sl.inset().dimension(*this);
1801 //lyxerr << "Cursor::getPos, i: "
1802 // << i << " x: " << xx << " y: " << y << endl;
1805 // Add contribution of initial rows of outermost paragraph
1806 CursorSlice const & sl = dit[0];
1807 TextMetrics const & tm = textMetrics(sl.text());
1808 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
1809 BOOST_ASSERT(!pm.rows().empty());
1810 y -= pm.rows()[0].ascent();
1812 // FIXME: document this mess
1814 if (sl.pos() > 0 && dit.depth() == 1) {
1816 if (pos && boundary)
1818 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << std::endl;
1819 rend = pm.pos2row(pos);
1821 rend = pm.pos2row(sl.pos());
1823 size_t rend = pm.pos2row(sl.pos());
1825 for (size_t rit = 0; rit != rend; ++rit)
1826 y += pm.rows()[rit].height();
1827 y += pm.rows()[rend].ascent();
1829 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
1831 // Make relative position from the nested inset now bufferview absolute.
1832 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
1835 // In the RTL case place the nested inset at the left of the cursor in
1836 // the outer paragraph
1837 bool boundary_1 = boundary && 1 == dit.depth();
1838 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
1846 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
1848 CursorSlice const & bot = dit.bottom();
1849 TextMetrics const & tm = textMetrics(bot.text());
1850 if (!tm.has(bot.pit()))
1851 return Point(-1, -1);
1853 Point p = coordOffset(dit, boundary); // offset from outer paragraph
1854 p.y_ += tm.parMetrics(bot.pit()).position();
1859 void BufferView::draw(frontend::Painter & pain)
1861 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
1862 Text & text = buffer_.text();
1863 TextMetrics const & tm = d->text_metrics_[&text];
1864 int const y = - d->offset_ref_ + tm.parMetrics(d->anchor_ref_).ascent();
1865 PainterInfo pi(this, pain);
1867 switch (d->update_strategy_) {
1869 case NoScreenUpdate:
1870 // If no screen painting is actually needed, only some the different
1871 // coordinates of insets and paragraphs needs to be updated.
1872 pi.full_repaint = true;
1873 pi.pain.setDrawingEnabled(false);
1877 case SingleParUpdate:
1878 pi.full_repaint = false;
1879 // In general, only the current row of the outermost paragraph
1880 // will be redrawn. Particular cases where selection spans
1881 // multiple paragraph are correctly detected in TextMetrics.
1885 case DecorationUpdate:
1886 // FIXME: We should also distinguish DecorationUpdate to avoid text
1887 // drawing if possible. This is not possible to do easily right now
1888 // because of the single backing pixmap.
1890 case FullScreenUpdate:
1891 // The whole screen, including insets, will be refreshed.
1892 pi.full_repaint = true;
1894 // Clear background.
1895 pain.fillRectangle(0, 0, width_, height_,
1896 buffer_.inset().backgroundColor());
1899 // and possibly grey out below
1900 std::pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1901 int const y2 = lastpm.second->position() + lastpm.second->descent();
1903 pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
1907 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
1911 void BufferView::message(docstring const & msg)
1914 d->gui_->message(msg);
1918 void BufferView::showDialog(std::string const & name)
1921 d->gui_->showDialog(name, string());
1925 void BufferView::showDialog(std::string const & name,
1926 std::string const & data, Inset * inset)
1929 d->gui_->showDialog(name, data, inset);
1933 void BufferView::updateDialog(std::string const & name, std::string const & data)
1936 d->gui_->updateDialog(name, data);
1940 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
1946 // FIXME: Move this out of BufferView again
1947 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
1949 if (!fname.isReadableFile()) {
1950 docstring const error = from_ascii(strerror(errno));
1951 docstring const file = makeDisplayPath(fname.absFilename(), 50);
1952 docstring const text =
1953 bformat(_("Could not read the specified document\n"
1954 "%1$s\ndue to the error: %2$s"), file, error);
1955 Alert::error(_("Could not read file"), text);
1959 if (!fname.isReadableFile()) {
1960 docstring const file = makeDisplayPath(fname.absFilename(), 50);
1961 docstring const text =
1962 bformat(_("%1$s\n is not readable."), file);
1963 Alert::error(_("Could not open file"), text);
1967 // FIXME UNICODE: We don't know the encoding of the file
1968 docstring file_content = fname.fileContents("UTF-8");
1969 if (file_content.empty()) {
1970 Alert::error(_("Reading not UTF-8 encoded file"),
1971 _("The file is not UTF-8 encoded.\n"
1972 "It will be read as local 8Bit-encoded.\n"
1973 "If this does not give the correct result\n"
1974 "then please change the encoding of the file\n"
1975 "to UTF-8 with a program other than LyX.\n"));
1976 file_content = fname.fileContents("local8bit");
1979 return normalize_c(file_content);
1983 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
1985 docstring const tmpstr = contentsOfPlaintextFile(f);
1990 Cursor & cur = cursor();
1991 cap::replaceSelection(cur);
1992 buffer_.undo().recordUndo(cur);
1994 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
1996 cur.innerText()->insertStringAsLines(cur, tmpstr);