3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alfredo Braunstein
7 * \author Lars Gullik Bjønnes
10 * \author Jürgen Vigna
12 * Full author contact details are available in file CREDITS.
17 #include "BufferView.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "CoordCache.h"
25 #include "CutAndPaste.h"
26 #include "DispatchResult.h"
27 #include "EmbeddedFiles.h"
28 #include "ErrorList.h"
30 #include "FloatList.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
34 #include "InsetIterator.h"
36 #include "LaTeXFeatures.h"
42 #include "MetricsInfo.h"
43 #include "Paragraph.h"
44 #include "paragraph_funcs.h"
45 #include "ParagraphParameters.h"
46 #include "ParIterator.h"
49 #include "TextClass.h"
50 #include "TextMetrics.h"
53 #include "WordLangTuple.h"
55 #include "insets/InsetBibtex.h"
56 #include "insets/InsetCommand.h" // ChangeRefs
57 #include "insets/InsetRef.h"
58 #include "insets/InsetText.h"
60 #include "frontends/alert.h"
61 #include "frontends/Delegates.h"
62 #include "frontends/FontMetrics.h"
63 #include "frontends/Painter.h"
64 #include "frontends/Selection.h"
66 #include "graphics/Previews.h"
68 #include "support/convert.h"
69 #include "support/debug.h"
70 #include "support/FileFilterList.h"
71 #include "support/filetools.h"
72 #include "support/gettext.h"
73 #include "support/lstrings.h"
74 #include "support/Package.h"
75 #include "support/types.h"
84 using namespace lyx::support;
88 namespace Alert = frontend::Alert;
92 /// Return an inset of this class if it exists at the current cursor position
94 T * getInsetByCode(Cursor const & cur, InsetCode code)
97 Inset * inset = it.nextInset();
98 if (inset && inset->lyxCode() == code)
99 return static_cast<T*>(inset);
104 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
107 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
108 docstring const & contents)
110 DocIterator tmpdit = dit;
113 Inset const * inset = tmpdit.nextInset();
115 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
116 && (contents.empty() ||
117 static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
121 tmpdit.forwardInset();
128 /// Looks for next inset with one of the given codes.
129 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
133 DocIterator tmpdit = dit;
134 tmpdit.forwardInset();
139 Inset const * inset = tmpdit.nextInset();
141 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
142 contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
146 if (!findNextInset(tmpdit, codes, contents)) {
147 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
148 tmpdit = doc_iterator_begin(tmpdit.bottom().inset());
149 if (!findNextInset(tmpdit, codes, contents))
160 /// Looks for next inset with the given code
161 void findInset(DocIterator & dit, InsetCode code, bool same_content)
163 findInset(dit, vector<InsetCode>(1, code), same_content);
167 /// Moves cursor to the next inset with one of the given codes.
168 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
171 Cursor tmpcur = bv->cursor();
172 if (!findInset(tmpcur, codes, same_content)) {
173 bv->cursor().message(_("No more insets"));
177 tmpcur.clearSelection();
178 bv->setCursor(tmpcur);
183 /// Moves cursor to the next inset with given code.
184 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
186 gotoInset(bv, vector<InsetCode>(1, code), same_content);
190 /// A map from a Text to the associated text metrics
191 typedef map<Text const *, TextMetrics> TextMetricsCache;
193 enum ScreenUpdateStrategy {
203 /////////////////////////////////////////////////////////////////////
207 /////////////////////////////////////////////////////////////////////
209 struct BufferView::Private
211 Private(BufferView & bv): wh_(0), cursor_(bv),
212 anchor_pit_(0), anchor_ypos_(0),
213 last_inset_(0), gui_(0)
217 ScrollbarParameters scrollbarParameters_;
219 ScreenUpdateStrategy update_strategy_;
221 CoordCache coord_cache_;
223 /// Estimated average par height for scrollbar.
225 /// this is used to handle XSelection events in the right manner.
234 pit_type anchor_pit_;
238 vector<int> par_height_;
240 /// keyboard mapping object.
243 /// last visited inset.
244 /** kept to send setMouseHover(false).
245 * Not owned, so don't delete.
249 mutable TextMetricsCache text_metrics_;
252 /** Not owned, so don't delete.
254 frontend::GuiBufferViewDelegate * gui_;
258 BufferView::BufferView(Buffer & buf)
259 : width_(0), height_(0), buffer_(buf), d(new Private(*this))
261 d->xsel_cache_.set = false;
262 d->intl_.initKeyMapper(lyxrc.use_kbmap);
264 d->cursor_.push(buffer_.inset());
265 d->cursor_.resetAnchor();
266 d->cursor_.setCurrentFont();
268 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
269 graphics::Previews::get().generateBufferPreviews(buffer_);
273 BufferView::~BufferView()
275 // current buffer is going to be switched-off, save cursor pos
276 // Ideally, the whole cursor stack should be saved, but session
277 // currently can only handle bottom (whole document) level pit and pos.
278 // That is to say, if a cursor is in a nested inset, it will be
279 // restore to the left of the top level inset.
280 LastFilePosSection::FilePos fp;
281 fp.pit = d->cursor_.bottom().pit();
282 fp.pos = d->cursor_.bottom().pos();
283 LyX::ref().session().lastFilePos().save(buffer_.fileName(), fp);
289 Intl & BufferView::getIntl()
295 Intl const & BufferView::getIntl() const
301 CoordCache & BufferView::coordCache()
303 return d->coord_cache_;
307 CoordCache const & BufferView::coordCache() const
309 return d->coord_cache_;
313 Buffer & BufferView::buffer()
319 Buffer const & BufferView::buffer() const
325 bool BufferView::fitCursor()
327 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
328 frontend::FontMetrics const & fm =
329 theFontMetrics(d->cursor_.getFont().fontInfo());
330 int const asc = fm.maxAscent();
331 int const des = fm.maxDescent();
332 Point const p = getPos(d->cursor_, d->cursor_.boundary());
333 if (p.y_ - asc >= 0 && p.y_ + des < height_)
340 void BufferView::processUpdateFlags(Update::flags flags)
342 // last_inset_ points to the last visited inset. This pointer may become
343 // invalid because of keyboard editing. Since all such operations
344 // causes screen update(), I reset last_inset_ to avoid such a problem.
346 // This is close to a hot-path.
347 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
348 << "[fitcursor = " << (flags & Update::FitCursor)
349 << ", forceupdate = " << (flags & Update::Force)
350 << ", singlepar = " << (flags & Update::SinglePar)
351 << "] buffer: " << &buffer_);
353 buffer_.updateMacros();
355 // Now do the first drawing step if needed. This consists on updating
356 // the CoordCache in updateMetrics().
357 // The second drawing step is done in WorkArea::redraw() if needed.
359 // Case when no explicit update is requested.
361 // no need to redraw anything.
362 d->update_strategy_ = NoScreenUpdate;
366 if (flags == Update::Decoration) {
367 d->update_strategy_ = DecorationUpdate;
372 if (flags == Update::FitCursor
373 || flags == (Update::Decoration | Update::FitCursor)) {
374 // tell the frontend to update the screen if needed.
379 if (flags & Update::Decoration) {
380 d->update_strategy_ = DecorationUpdate;
384 // no screen update is needed.
385 d->update_strategy_ = NoScreenUpdate;
389 bool const full_metrics = flags & Update::Force || !singleParUpdate();
392 // We have to update the full screen metrics.
395 if (!(flags & Update::FitCursor)) {
396 // Nothing to do anymore. Trigger a redraw and return
401 // updateMetrics() does not update paragraph position
402 // This is done at draw() time. So we need a redraw!
406 // The cursor is off screen so ensure it is visible.
413 void BufferView::updateScrollbar()
418 Text & t = buffer_.text();
419 TextMetrics & tm = d->text_metrics_[&t];
421 LYXERR(Debug::GUI, " Updating scrollbar: height: "
422 << t.paragraphs().size()
423 << " curr par: " << d->cursor_.bottom().pit()
424 << " default height " << defaultRowHeight());
426 int const parsize = int(t.paragraphs().size());
427 if (d->par_height_.size() != parsize) {
428 d->par_height_.clear();
429 // FIXME: We assume a default paragraph height of 2 rows. This
430 // should probably be pondered with the screen width.
431 d->par_height_.resize(parsize, defaultRowHeight() * 2);
434 // It would be better to fix the scrollbar to understand
435 // values in [0..1] and divide everything by wh
437 // Look at paragraph heights on-screen
438 pit_type first_visible_pit = -1;
439 pair<pit_type, ParagraphMetrics const *> first = tm.first();
440 pair<pit_type, ParagraphMetrics const *> last = tm.last();
441 for (pit_type pit = first.first; pit <= last.first; ++pit) {
442 ParagraphMetrics const & pm = tm.parMetrics(pit);
443 d->par_height_[pit] = pm.height();
444 if (first_visible_pit >= 0 || pm.position() + pm.descent() <= 0)
446 first_visible_pit = pit;
447 LYXERR(Debug::SCROLLING, "first visible pit " << first_visible_pit);
448 // FIXME: we should look for the first visible row within
449 // the deepest inset!
450 int row_pos = pm.position();
451 size_t const nrows = pm.rows().size();
452 for (size_t i = 0; i != nrows; ++i) {
453 Row const & row = pm.rows()[i];
455 LYXERR(Debug::SCROLLING, "first visible row " << i
456 << "(row pos = " << row_pos << ");");
459 row_pos += row.height();
461 d->scrollbarParameters_.position = row_pos;
464 d->scrollbarParameters_.height = 0;
465 for (size_t i = 0; i != d->par_height_.size(); ++i) {
466 if (i == first_visible_pit)
467 d->scrollbarParameters_.position += d->scrollbarParameters_.height;
468 d->scrollbarParameters_.height += d->par_height_[i];
471 // We prefer fixed size line scrolling.
472 d->scrollbarParameters_.lineScrollHeight = defaultRowHeight();
476 ScrollbarParameters const & BufferView::scrollbarParameters() const
478 return d->scrollbarParameters_;
482 void BufferView::scrollDocView(int value)
484 int const offset = value - d->scrollbarParameters_.position;
485 // If the offset is less than 2 screen height, prefer to scroll instead.
486 if (abs(offset) <= 2 * height_) {
492 for (size_t i = 0; i != d->par_height_.size(); ++i) {
493 par_pos += d->par_height_[i];
494 if (par_pos >= value) {
495 d->anchor_pit_ = pit_type(i);
500 LYXERR(Debug::SCROLLING, "value = " << value
501 << "\tanchor_ref_ = " << d->anchor_pit_
502 << "\tpar_pos = " << par_pos);
504 d->anchor_ypos_ = par_pos - value;
510 // FIXME: this method is not working well.
511 void BufferView::setCursorFromScrollbar()
513 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
515 int const height = 2 * defaultRowHeight();
516 int const first = height;
517 int const last = height_ - height;
518 Cursor & cur = d->cursor_;
520 switch (cursorStatus(cur)) {
522 // We reset the cursor because cursorStatus() does not
523 // work when the cursor is within mathed.
524 cur.reset(buffer_.inset());
525 tm.setCursorFromCoordinates(cur, 0, first);
526 cur.clearSelection();
529 // We reset the cursor because cursorStatus() does not
530 // work when the cursor is within mathed.
531 cur.reset(buffer_.inset());
532 tm.setCursorFromCoordinates(cur, 0, last);
533 cur.clearSelection();
536 int const y = getPos(cur, cur.boundary()).y_;
537 int const newy = min(last, max(y, first));
539 cur.reset(buffer_.inset());
540 tm.setCursorFromCoordinates(cur, 0, newy);
546 Change const BufferView::getCurrentChange() const
548 if (!d->cursor_.selection())
549 return Change(Change::UNCHANGED);
551 DocIterator dit = d->cursor_.selectionBegin();
552 return dit.paragraph().lookupChange(dit.pos());
556 // this could be used elsewhere as well?
557 // FIXME: This does not work within mathed!
558 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
560 Point const p = getPos(dit, dit.boundary());
563 if (p.y_ > workHeight())
569 void BufferView::saveBookmark(unsigned int idx)
571 // tenatively save bookmark, id and pos will be used to
572 // acturately locate a bookmark in a 'live' lyx session.
573 // pit and pos will be updated with bottom level pit/pos
575 LyX::ref().session().bookmarks().save(
577 d->cursor_.bottom().pit(),
578 d->cursor_.bottom().pos(),
579 d->cursor_.paragraph().id(),
584 // emit message signal.
585 message(_("Save bookmark"));
589 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
590 int top_id, pos_type top_pos)
592 bool success = false;
595 d->cursor_.clearSelection();
597 // if a valid par_id is given, try it first
598 // This is the case for a 'live' bookmark when unique paragraph ID
599 // is used to track bookmarks.
601 ParIterator par = buffer_.getParFromID(top_id);
602 if (par != buffer_.par_iterator_end()) {
603 doc_it = makeDocIterator(par, min(par->size(), top_pos));
604 // Some slices of the iterator may not be
605 // reachable (e.g. closed collapsable inset)
606 // so the dociterator may need to be
607 // shortened. Otherwise, setCursor may crash
608 // lyx when the cursor can not be set to these
610 size_t const n = doc_it.depth();
611 for (size_t i = 0; i < n; ++i)
612 if (doc_it[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
620 // if top_id == 0, or searching through top_id failed
621 // This is the case for a 'restored' bookmark when only bottom
622 // (document level) pit was saved. Because of this, bookmark
623 // restoration is inaccurate. If a bookmark was within an inset,
624 // it will be restored to the left of the outmost inset that contains
626 if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
627 doc_it = doc_iterator_begin(buffer_.inset());
628 doc_it.pit() = bottom_pit;
629 doc_it.pos() = min(bottom_pos, doc_it.paragraph().size());
634 // Note: only bottom (document) level pit is set.
636 // set the current font.
637 d->cursor_.setCurrentFont();
638 // To center the screen on this new position we need the
639 // paragraph position which is computed at draw() time.
640 // So we need a redraw!
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::showCursor()
674 // We are not properly started yet, delay until resizing is
679 LYXERR(Debug::SCROLLING, "recentering!");
681 CursorSlice & bot = d->cursor_.bottom();
682 TextMetrics & tm = d->text_metrics_[bot.text()];
684 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
685 int bot_pit = d->cursor_.bottom().pit();
686 if (bot_pit > max_pit) {
687 // FIXME: Why does this happen?
688 LYXERR0("bottom pit is greater that max pit: "
689 << bot_pit << " > " << max_pit);
693 if (bot_pit == tm.first().first - 1)
694 tm.newParMetricsUp();
695 else if (bot_pit == tm.last().first + 1)
696 tm.newParMetricsDown();
698 if (tm.has(bot_pit)) {
699 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
700 int offset = coordOffset(d->cursor_, d->cursor_.boundary()).y_;
701 int ypos = pm.position() + offset;
702 Dimension const & row_dim = d->cursor_.textRow().dimension();
703 if (ypos - row_dim.ascent() < 0)
704 scrollUp(- ypos + row_dim.ascent());
705 else if (ypos + row_dim.descent() > height_)
706 scrollDown(ypos - height_ + row_dim.descent());
707 // else, nothing to do, the cursor is already visible so we just return.
711 tm.redoParagraph(bot_pit);
712 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
713 int offset = coordOffset(d->cursor_, d->cursor_.boundary()).y_;
715 d->anchor_pit_ = bot_pit;
716 Dimension const & row_dim = d->cursor_.textRow().dimension();
718 if (d->anchor_pit_ == 0)
719 d->anchor_ypos_ = offset + pm.ascent();
720 else if (d->anchor_pit_ == max_pit)
721 d->anchor_ypos_ = height_ - offset - row_dim.descent();
723 d->anchor_ypos_ = offset + pm.ascent() - height_ / 2;
730 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
734 Cursor & cur = d->cursor_;
736 switch (cmd.action) {
739 flag.enabled(buffer_.undo().hasUndoStack());
742 flag.enabled(buffer_.undo().hasRedoStack());
744 case LFUN_FILE_INSERT:
745 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
746 case LFUN_FILE_INSERT_PLAINTEXT:
747 case LFUN_BOOKMARK_SAVE:
748 // FIXME: Actually, these LFUNS should be moved to Text
749 flag.enabled(cur.inTexted());
751 case LFUN_FONT_STATE:
752 case LFUN_LABEL_INSERT:
753 case LFUN_INFO_INSERT:
754 case LFUN_PARAGRAPH_GOTO:
756 case LFUN_REFERENCE_NEXT:
758 case LFUN_WORD_REPLACE:
761 case LFUN_MARK_TOGGLE:
762 case LFUN_SCREEN_RECENTER:
763 case LFUN_BIBTEX_DATABASE_ADD:
764 case LFUN_BIBTEX_DATABASE_DEL:
765 case LFUN_WORDS_COUNT:
766 case LFUN_NEXT_INSET_TOGGLE:
770 case LFUN_LABEL_GOTO: {
771 flag.enabled(!cmd.argument().empty()
772 || getInsetByCode<InsetRef>(cur, REF_CODE));
776 case LFUN_CHANGES_TRACK:
778 flag.setOnOff(buffer_.params().trackChanges);
781 case LFUN_CHANGES_OUTPUT:
783 flag.setOnOff(buffer_.params().outputChanges);
786 case LFUN_CHANGES_MERGE:
787 case LFUN_CHANGE_NEXT:
788 case LFUN_ALL_CHANGES_ACCEPT:
789 case LFUN_ALL_CHANGES_REJECT:
790 // TODO: context-sensitive enabling of LFUNs
791 // In principle, these command should only be enabled if there
792 // is a change in the document. However, without proper
793 // optimizations, this will inevitably result in poor performance.
797 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
798 flag.setOnOff(buffer_.params().compressed);
802 case LFUN_BUFFER_TOGGLE_EMBEDDING: {
803 flag.setOnOff(buffer_.params().embedded);
808 case LFUN_SCREEN_DOWN:
812 // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
813 // everywhere else before this can enabled:
814 case LFUN_SCREEN_UP_SELECT:
815 case LFUN_SCREEN_DOWN_SELECT:
819 case LFUN_LAYOUT_TABULAR:
820 flag.enabled(cur.innerInsetOfType(TABULAR_CODE));
824 case LFUN_LAYOUT_PARAGRAPH:
825 flag.enabled(cur.inset().forceDefaultParagraphs(cur.idx()));
828 case LFUN_INSET_SETTINGS: {
829 InsetCode code = cur.inset().lyxCode();
833 enable = cmd.argument() == "tabular";
836 enable = cmd.argument() == "ert";
839 enable = cmd.argument() == "float";
842 enable = cmd.argument() == "wrap";
845 enable = cmd.argument() == "note";
848 enable = cmd.argument() == "branch";
851 enable = cmd.argument() == "box";
854 enable = cmd.argument() == "listings";
859 flag.enabled(enable);
863 case LFUN_DIALOG_SHOW_NEW_INSET:
864 flag.enabled(cur.inset().lyxCode() != ERT_CODE &&
865 cur.inset().lyxCode() != LISTINGS_CODE);
866 if (cur.inset().lyxCode() == CAPTION_CODE) {
868 if (cur.inset().getStatus(cur, cmd, flag))
881 bool BufferView::dispatch(FuncRequest const & cmd)
883 //lyxerr << [ cmd = " << cmd << "]" << endl;
885 // Make sure that the cached BufferView is correct.
886 LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
887 << " arg[" << to_utf8(cmd.argument()) << ']'
888 << " x[" << cmd.x << ']'
889 << " y[" << cmd.y << ']'
890 << " button[" << cmd.button() << ']');
892 Cursor & cur = d->cursor_;
894 switch (cmd.action) {
897 cur.message(_("Undo"));
898 cur.clearSelection();
900 cur.message(_("No further undo information"));
904 cur.message(_("Redo"));
905 cur.clearSelection();
907 cur.message(_("No further redo information"));
910 case LFUN_FONT_STATE:
911 cur.message(cur.currentState());
914 case LFUN_BOOKMARK_SAVE:
915 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
918 case LFUN_LABEL_GOTO: {
919 docstring label = cmd.argument();
922 getInsetByCode<InsetRef>(d->cursor_,
925 label = inset->getParam("reference");
926 // persistent=false: use temp_bookmark
936 case LFUN_PARAGRAPH_GOTO: {
937 int const id = convert<int>(to_utf8(cmd.argument()));
939 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
940 b = theBufferList().next(b)) {
942 ParIterator par = b->getParFromID(id);
943 if (par == b->par_iterator_end()) {
944 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
946 LYXERR(Debug::INFO, "Paragraph " << par->id()
947 << " found in buffer `"
948 << b->absFileName() << "'.");
952 setCursor(makeDocIterator(par, 0));
955 // Switch to other buffer view and resend cmd
956 theLyXFunc().dispatch(FuncRequest(
957 LFUN_BUFFER_SWITCH, b->absFileName()));
958 theLyXFunc().dispatch(cmd);
968 gotoInset(this, NOTE_CODE, false);
971 case LFUN_REFERENCE_NEXT: {
972 vector<InsetCode> tmp;
973 tmp.push_back(LABEL_CODE);
974 tmp.push_back(REF_CODE);
975 gotoInset(this, tmp, true);
979 case LFUN_CHANGES_TRACK:
980 buffer_.params().trackChanges = !buffer_.params().trackChanges;
983 case LFUN_CHANGES_OUTPUT:
984 buffer_.params().outputChanges = !buffer_.params().outputChanges;
985 if (buffer_.params().outputChanges) {
986 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
987 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
988 LaTeXFeatures::isAvailable("xcolor");
990 if (!dvipost && !xcolorsoul) {
991 Alert::warning(_("Changes not shown in LaTeX output"),
992 _("Changes will not be highlighted in LaTeX output, "
993 "because neither dvipost nor xcolor/soul are installed.\n"
994 "Please install these packages or redefine "
995 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
996 } else if (!xcolorsoul) {
997 Alert::warning(_("Changes not shown in LaTeX output"),
998 _("Changes will not be highlighted in LaTeX output "
999 "when using pdflatex, because xcolor and soul are not installed.\n"
1000 "Please install both packages or redefine "
1001 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1006 case LFUN_CHANGE_NEXT:
1007 findNextChange(this);
1010 case LFUN_CHANGES_MERGE:
1011 if (findNextChange(this))
1012 showDialog("changes");
1015 case LFUN_ALL_CHANGES_ACCEPT:
1016 // select complete document
1017 d->cursor_.reset(buffer_.inset());
1018 d->cursor_.selHandle(true);
1019 buffer_.text().cursorBottom(d->cursor_);
1020 // accept everything in a single step to support atomic undo
1021 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1024 case LFUN_ALL_CHANGES_REJECT:
1025 // select complete document
1026 d->cursor_.reset(buffer_.inset());
1027 d->cursor_.selHandle(true);
1028 buffer_.text().cursorBottom(d->cursor_);
1029 // reject everything in a single step to support atomic undo
1030 // Note: reject does not work recursively; the user may have to repeat the operation
1031 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1034 case LFUN_WORD_FIND:
1038 case LFUN_WORD_REPLACE: {
1039 bool has_deleted = false;
1040 if (cur.selection()) {
1041 DocIterator beg = cur.selectionBegin();
1042 DocIterator end = cur.selectionEnd();
1043 if (beg.pit() == end.pit()) {
1044 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1045 if (cur.paragraph().isDeleted(p))
1050 replace(this, cmd, has_deleted);
1055 cur.clearSelection();
1057 cur.message(from_utf8(N_("Mark off")));
1061 cur.clearSelection();
1064 cur.message(from_utf8(N_("Mark on")));
1067 case LFUN_MARK_TOGGLE:
1068 cur.clearSelection();
1071 cur.message(from_utf8(N_("Mark removed")));
1074 cur.message(from_utf8(N_("Mark set")));
1079 case LFUN_SCREEN_RECENTER:
1083 case LFUN_BIBTEX_DATABASE_ADD: {
1084 Cursor tmpcur = d->cursor_;
1085 findInset(tmpcur, BIBTEX_CODE, false);
1086 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1089 if (inset->addDatabase(to_utf8(cmd.argument())))
1090 buffer_.updateBibfilesCache();
1095 case LFUN_BIBTEX_DATABASE_DEL: {
1096 Cursor tmpcur = d->cursor_;
1097 findInset(tmpcur, BIBTEX_CODE, false);
1098 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1101 if (inset->delDatabase(to_utf8(cmd.argument())))
1102 buffer_.updateBibfilesCache();
1107 case LFUN_WORDS_COUNT: {
1108 DocIterator from, to;
1109 if (cur.selection()) {
1110 from = cur.selectionBegin();
1111 to = cur.selectionEnd();
1113 from = doc_iterator_begin(buffer_.inset());
1114 to = doc_iterator_end(buffer_.inset());
1116 int const count = countWords(from, to);
1119 if (cur.selection())
1120 message = bformat(_("%1$d words in selection."),
1123 message = bformat(_("%1$d words in document."),
1127 if (cur.selection())
1128 message = _("One word in selection.");
1130 message = _("One word in document.");
1133 Alert::information(_("Count words"), message);
1137 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1138 // turn compression on/off
1139 buffer_.params().compressed = !buffer_.params().compressed;
1142 case LFUN_BUFFER_TOGGLE_EMBEDDING:
1143 // turn embedding on/off
1144 buffer_.embeddedFiles().enable(!buffer_.params().embedded);
1147 case LFUN_NEXT_INSET_TOGGLE: {
1148 // this is the real function we want to invoke
1149 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1150 // if there is an inset at cursor, see whether it
1152 Inset * inset = cur.nextInset();
1154 if (inset->isActive()) {
1155 Cursor tmpcur = cur;
1156 tmpcur.pushBackward(*inset);
1157 inset->dispatch(tmpcur, tmpcmd);
1158 if (tmpcur.result().dispatched()) {
1161 } else if (inset->editable() == Inset::IS_EDITABLE) {
1162 inset->edit(cur, true);
1165 // if it did not work, try the underlying inset.
1166 if (!cur.result().dispatched())
1167 cur.dispatch(tmpcmd);
1169 if (cur.result().dispatched())
1170 cur.clearSelection();
1175 case LFUN_SCREEN_UP:
1176 case LFUN_SCREEN_DOWN: {
1177 Point p = getPos(cur, cur.boundary());
1178 if (p.y_ < 0 || p.y_ > height_) {
1179 // The cursor is off-screen so recenter before proceeding.
1181 p = getPos(cur, cur.boundary());
1183 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1184 cur.reset(buffer_.inset());
1185 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1186 //FIXME: what to do with cur.x_target()?
1191 case LFUN_SCREEN_UP_SELECT:
1192 case LFUN_SCREEN_DOWN_SELECT: {
1193 // Those two are not ready yet for consumption.
1196 cur.selHandle(true);
1197 size_t initial_depth = cur.depth();
1198 Point const p = getPos(cur, cur.boundary());
1199 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1200 // FIXME: We need to verify if the cursor stayed within an inset...
1201 //cur.reset(buffer_.inset());
1202 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1204 while (cur.depth() > initial_depth) {
1207 // FIXME: we need to do a redraw again because of the selection
1208 // But no screen update is needed.
1209 d->update_strategy_ = NoScreenUpdate;
1222 docstring const BufferView::requestSelection()
1224 Cursor & cur = d->cursor_;
1226 if (!cur.selection()) {
1227 d->xsel_cache_.set = false;
1231 if (!d->xsel_cache_.set ||
1232 cur.top() != d->xsel_cache_.cursor ||
1233 cur.anchor_.top() != d->xsel_cache_.anchor)
1235 d->xsel_cache_.cursor = cur.top();
1236 d->xsel_cache_.anchor = cur.anchor_.top();
1237 d->xsel_cache_.set = cur.selection();
1238 return cur.selectionAsString(false);
1244 void BufferView::clearSelection()
1246 d->cursor_.clearSelection();
1247 // Clear the selection buffer. Otherwise a subsequent
1248 // middle-mouse-button paste would use the selection buffer,
1249 // not the more current external selection.
1250 cap::clearSelection();
1251 d->xsel_cache_.set = false;
1252 // The buffer did not really change, but this causes the
1253 // redraw we need because we cleared the selection above.
1258 void BufferView::resize(int width, int height)
1260 // Update from work area
1264 // Clear the paragraph height cache.
1265 d->par_height_.clear();
1271 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1273 TextMetrics & tm = d->text_metrics_[&text];
1274 Inset * inset = tm.checkInsetHit(x, y);
1278 if (!inset->descendable())
1279 // No need to go further down if the inset is not
1283 size_t cell_number = inset->nargs();
1284 // Check all the inner cell.
1285 for (size_t i = 0; i != cell_number; ++i) {
1286 Text const * inner_text = inset->getText(i);
1289 Inset const * inset_deeper =
1290 getCoveringInset(*inner_text, x, y);
1292 return inset_deeper;
1300 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1302 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1304 // This is only called for mouse related events including
1305 // LFUN_FILE_OPEN generated by drag-and-drop.
1306 FuncRequest cmd = cmd0;
1309 cur.push(buffer_.inset());
1310 cur.selection() = d->cursor_.selection();
1312 // Either the inset under the cursor or the
1313 // surrounding Text will handle this event.
1315 // make sure we stay within the screen...
1316 cmd.y = min(max(cmd.y, -1), height_);
1318 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1320 // Get inset under mouse, if there is one.
1321 Inset const * covering_inset =
1322 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1323 if (covering_inset == d->last_inset_)
1324 // Same inset, no need to do anything...
1327 bool need_redraw = false;
1328 // const_cast because of setMouseHover().
1329 Inset * inset = const_cast<Inset *>(covering_inset);
1331 // Remove the hint on the last hovered inset (if any).
1332 need_redraw |= d->last_inset_->setMouseHover(false);
1334 // Highlighted the newly hovered inset (if any).
1335 need_redraw |= inset->setMouseHover(true);
1336 d->last_inset_ = inset;
1340 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1341 << cmd.x << ", " << cmd.y << ")");
1343 d->update_strategy_ = DecorationUpdate;
1345 // This event (moving without mouse click) is not passed further.
1346 // This should be changed if it is further utilized.
1351 // Build temporary cursor.
1352 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1354 // Put anchor at the same position.
1357 // Try to dispatch to an non-editable inset near this position
1358 // via the temp cursor. If the inset wishes to change the real
1359 // cursor it has to do so explicitly by using
1360 // cur.bv().cursor() = cur; (or similar)
1362 inset->dispatch(cur, cmd);
1364 // Now dispatch to the temporary cursor. If the real cursor should
1365 // be modified, the inset's dispatch has to do so explicitly.
1366 if (!cur.result().dispatched())
1369 //Do we have a selection?
1370 theSelection().haveSelection(cursor().selection());
1372 // If the command has been dispatched,
1373 if (cur.result().dispatched()
1374 // an update is asked,
1375 && cur.result().update())
1376 processUpdateFlags(cur.result().update());
1380 void BufferView::scroll(int y)
1389 void BufferView::scrollDown(int offset)
1391 Text * text = &buffer_.text();
1392 TextMetrics & tm = d->text_metrics_[text];
1393 int ymax = height_ + offset;
1395 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1396 int bottom_pos = last.second->position() + last.second->descent();
1397 if (last.first + 1 == int(text->paragraphs().size())) {
1398 if (bottom_pos <= height_)
1400 offset = min(offset, bottom_pos - height_);
1403 if (bottom_pos > ymax)
1405 tm.newParMetricsDown();
1407 d->anchor_ypos_ -= offset;
1413 void BufferView::scrollUp(int offset)
1415 Text * text = &buffer_.text();
1416 TextMetrics & tm = d->text_metrics_[text];
1417 int ymin = - offset;
1419 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1420 int top_pos = first.second->position() - first.second->ascent();
1421 if (first.first == 0) {
1424 offset = min(offset, - top_pos);
1429 tm.newParMetricsUp();
1431 d->anchor_ypos_ += offset;
1437 void BufferView::setCursorFromRow(int row)
1442 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1444 d->cursor_.reset(buffer_.inset());
1446 buffer_.text().setCursor(d->cursor_, 0, 0);
1448 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1452 void BufferView::gotoLabel(docstring const & label)
1454 for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1455 vector<docstring> labels;
1456 it->getLabelList(buffer_, labels);
1457 if (find(labels.begin(), labels.end(), label) != labels.end()) {
1466 TextMetrics const & BufferView::textMetrics(Text const * t) const
1468 return const_cast<BufferView *>(this)->textMetrics(t);
1472 TextMetrics & BufferView::textMetrics(Text const * t)
1474 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
1475 if (tmc_it == d->text_metrics_.end()) {
1476 tmc_it = d->text_metrics_.insert(
1477 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1479 return tmc_it->second;
1483 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1486 return textMetrics(t).parMetrics(pit);
1490 int BufferView::workHeight() const
1496 void BufferView::setCursor(DocIterator const & dit)
1498 size_t const n = dit.depth();
1499 for (size_t i = 0; i < n; ++i)
1500 dit[i].inset().edit(d->cursor_, true);
1502 d->cursor_.setCursor(dit);
1503 d->cursor_.selection() = false;
1507 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1509 // Would be wrong to delete anything if we have a selection.
1510 if (cur.selection())
1513 bool need_anchor_change = false;
1514 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1515 need_anchor_change);
1517 if (need_anchor_change)
1523 updateLabels(buffer_);
1531 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1533 BOOST_ASSERT(&cur.bv() == this);
1536 // this event will clear selection so we save selection for
1537 // persistent selection
1538 cap::saveSelection(cursor());
1540 // Has the cursor just left the inset?
1541 bool badcursor = false;
1542 bool leftinset = (&d->cursor_.inset() != &cur.inset());
1544 badcursor = notifyCursorLeaves(d->cursor_, cur);
1546 // FIXME: shift-mouse selection doesn't work well across insets.
1547 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1549 // do the dEPM magic if needed
1550 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1551 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1552 // the leftinset bool would not be necessary (badcursor instead).
1553 bool update = leftinset;
1554 if (!do_selection && !badcursor && d->cursor_.inTexted())
1555 update |= checkDepm(cur, d->cursor_);
1557 // if the cursor was in an empty script inset and the new
1558 // position is in the nucleus of the inset, notifyCursorLeaves
1559 // will kill the script inset itself. So we check all the
1560 // elements of the cursor to make sure that they are correct.
1561 // For an example, see bug 2933:
1562 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1563 // The code below could maybe be moved to a DocIterator method.
1564 //lyxerr << "cur before " << cur <<endl;
1565 DocIterator dit(cur.inset());
1566 dit.push_back(cur.bottom());
1568 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1569 dit.push_back(cur[i]);
1572 //lyxerr << "5 cur after" << dit <<endl;
1574 d->cursor_.setCursor(dit);
1575 d->cursor_.boundary(cur.boundary());
1577 d->cursor_.setSelection();
1579 d->cursor_.clearSelection();
1581 d->cursor_.finishUndo();
1582 d->cursor_.setCurrentFont();
1587 void BufferView::putSelectionAt(DocIterator const & cur,
1588 int length, bool backwards)
1590 d->cursor_.clearSelection();
1596 d->cursor_.pos() += length;
1597 d->cursor_.setSelection(d->cursor_, -length);
1599 d->cursor_.setSelection(d->cursor_, length);
1604 Cursor & BufferView::cursor()
1610 Cursor const & BufferView::cursor() const
1616 pit_type BufferView::anchor_ref() const
1618 return d->anchor_pit_;
1622 bool BufferView::singleParUpdate()
1624 Text & buftext = buffer_.text();
1625 pit_type const bottom_pit = d->cursor_.bottom().pit();
1626 TextMetrics & tm = textMetrics(&buftext);
1627 int old_height = tm.parMetrics(bottom_pit).height();
1629 // In Single Paragraph mode, rebreak only
1630 // the (main text, not inset!) paragraph containing the cursor.
1631 // (if this paragraph contains insets etc., rebreaking will
1632 // recursively descend)
1633 tm.redoParagraph(bottom_pit);
1634 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
1635 if (pm.height() != old_height)
1636 // Paragraph height has changed so we cannot proceed to
1637 // the singlePar optimisation.
1640 d->update_strategy_ = SingleParUpdate;
1642 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
1643 << " y2: " << pm.position() + pm.descent()
1644 << " pit: " << bottom_pit
1645 << " singlepar: 1");
1650 void BufferView::updateMetrics()
1652 Text & buftext = buffer_.text();
1653 pit_type const npit = int(buftext.paragraphs().size());
1655 // Clear out the position cache in case of full screen redraw,
1656 d->coord_cache_.clear();
1658 // Clear out paragraph metrics to avoid having invalid metrics
1659 // in the cache from paragraphs not relayouted below
1660 // The complete text metrics will be redone.
1661 d->text_metrics_.clear();
1663 TextMetrics & tm = textMetrics(&buftext);
1665 // Rebreak anchor paragraph.
1666 tm.redoParagraph(d->anchor_pit_);
1667 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
1668 anchor_pm.setPosition(d->anchor_ypos_);
1670 LYXERR(Debug::PAINTING, "metrics: "
1671 << " anchor pit = " << d->anchor_pit_
1672 << " anchor ypos = " << d->anchor_ypos_);
1674 // Redo paragraphs above anchor if necessary.
1675 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
1676 // We are now just above the anchor paragraph.
1677 pit_type pit1 = d->anchor_pit_ - 1;
1678 for (; pit1 >= 0 && y1 >= 0; --pit1) {
1679 tm.redoParagraph(pit1);
1680 ParagraphMetrics & pm = tm.par_metrics_[pit1];
1682 // Save the paragraph position in the cache.
1687 // Redo paragraphs below the anchor if necessary.
1688 int y2 = d->anchor_ypos_ + anchor_pm.descent();
1689 // We are now just below the anchor paragraph.
1690 pit_type pit2 = d->anchor_pit_ + 1;
1691 for (; pit2 < npit && y2 <= height_; ++pit2) {
1692 tm.redoParagraph(pit2);
1693 ParagraphMetrics & pm = tm.par_metrics_[pit2];
1695 // Save the paragraph position in the cache.
1700 LYXERR(Debug::PAINTING, "Metrics: "
1701 << " anchor pit = " << d->anchor_pit_
1702 << " anchor ypos = " << d->anchor_ypos_
1705 << " pit1 = " << pit1
1706 << " pit2 = " << pit2);
1708 d->update_strategy_ = FullScreenUpdate;
1710 if (lyxerr.debugging(Debug::WORKAREA)) {
1711 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
1712 d->coord_cache_.dump();
1717 void BufferView::insertLyXFile(FileName const & fname)
1719 BOOST_ASSERT(d->cursor_.inTexted());
1721 // Get absolute path of file and add ".lyx"
1722 // to the filename if necessary
1723 FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
1725 docstring const disp_fn = makeDisplayPath(filename.absFilename());
1726 // emit message signal.
1727 message(bformat(_("Inserting document %1$s..."), disp_fn));
1730 Buffer buf("", false);
1731 if (buf.loadLyXFile(filename)) {
1732 ErrorList & el = buffer_.errorList("Parse");
1733 // Copy the inserted document error list into the current buffer one.
1734 el = buf.errorList("Parse");
1735 buffer_.undo().recordUndo(d->cursor_);
1736 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
1737 buf.params().getTextClassPtr(), el);
1738 res = _("Document %1$s inserted.");
1740 res = _("Could not insert document %1$s");
1745 // emit message signal.
1746 message(bformat(res, disp_fn));
1747 buffer_.errors("Parse");
1751 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1757 // Addup contribution of nested insets, from inside to outside,
1758 // keeping the outer paragraph for a special handling below
1759 for (size_t i = dit.depth() - 1; i >= 1; --i) {
1760 CursorSlice const & sl = dit[i];
1764 // get relative position inside sl.inset()
1765 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
1767 // Make relative position inside of the edited inset relative to sl.inset()
1771 // In case of an RTL inset, the edited inset will be positioned to the left
1774 bool boundary_i = boundary && i + 1 == dit.depth();
1775 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
1780 // remember width for the case that sl.inset() is positioned in an RTL inset
1781 if (i && dit[i - 1].text()) {
1782 // If this Inset is inside a Text Inset, retrieve the Dimension
1783 // from the containing text instead of using Inset::dimension() which
1784 // might not be implemented.
1785 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
1786 // elimination of Inset::dim_ cache. This coordOffset() method needs
1787 // to be rewritten in light of the new design.
1788 Dimension const & dim = parMetrics(dit[i - 1].text(),
1789 dit[i - 1].pit()).insetDimension(&sl.inset());
1792 Dimension const dim = sl.inset().dimension(*this);
1796 //lyxerr << "Cursor::getPos, i: "
1797 // << i << " x: " << xx << " y: " << y << endl;
1800 // Add contribution of initial rows of outermost paragraph
1801 CursorSlice const & sl = dit[0];
1802 TextMetrics const & tm = textMetrics(sl.text());
1803 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
1804 BOOST_ASSERT(!pm.rows().empty());
1805 y -= pm.rows()[0].ascent();
1807 // FIXME: document this mess
1809 if (sl.pos() > 0 && dit.depth() == 1) {
1811 if (pos && boundary)
1813 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
1814 rend = pm.pos2row(pos);
1816 rend = pm.pos2row(sl.pos());
1818 size_t rend = pm.pos2row(sl.pos());
1820 for (size_t rit = 0; rit != rend; ++rit)
1821 y += pm.rows()[rit].height();
1822 y += pm.rows()[rend].ascent();
1824 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
1826 // Make relative position from the nested inset now bufferview absolute.
1827 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
1830 // In the RTL case place the nested inset at the left of the cursor in
1831 // the outer paragraph
1832 bool boundary_1 = boundary && 1 == dit.depth();
1833 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
1841 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
1843 CursorSlice const & bot = dit.bottom();
1844 TextMetrics const & tm = textMetrics(bot.text());
1845 if (!tm.has(bot.pit()))
1846 return Point(-1, -1);
1848 Point p = coordOffset(dit, boundary); // offset from outer paragraph
1849 p.y_ += tm.parMetrics(bot.pit()).position();
1854 void BufferView::draw(frontend::Painter & pain)
1856 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
1857 Text & text = buffer_.text();
1858 TextMetrics const & tm = d->text_metrics_[&text];
1859 int const y = tm.first().second->position();
1860 PainterInfo pi(this, pain);
1862 switch (d->update_strategy_) {
1864 case NoScreenUpdate:
1865 // If no screen painting is actually needed, only some the different
1866 // coordinates of insets and paragraphs needs to be updated.
1867 pi.full_repaint = true;
1868 pi.pain.setDrawingEnabled(false);
1872 case SingleParUpdate:
1873 pi.full_repaint = false;
1874 // In general, only the current row of the outermost paragraph
1875 // will be redrawn. Particular cases where selection spans
1876 // multiple paragraph are correctly detected in TextMetrics.
1880 case DecorationUpdate:
1881 // FIXME: We should also distinguish DecorationUpdate to avoid text
1882 // drawing if possible. This is not possible to do easily right now
1883 // because of the single backing pixmap.
1885 case FullScreenUpdate:
1886 // The whole screen, including insets, will be refreshed.
1887 pi.full_repaint = true;
1889 // Clear background.
1890 pain.fillRectangle(0, 0, width_, height_,
1891 buffer_.inset().backgroundColor());
1896 // and possibly grey out below
1897 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1898 int const y2 = lastpm.second->position() + lastpm.second->descent();
1900 pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
1903 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
1905 // The scrollbar needs an update.
1908 // Normalize anchor for next time
1909 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
1910 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1911 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
1912 ParagraphMetrics const & pm = tm.parMetrics(pit);
1913 if (pm.position() + pm.descent() > 0) {
1914 d->anchor_pit_ = pit;
1915 d->anchor_ypos_ = pm.position();
1919 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
1920 << " anchor ypos = " << d->anchor_ypos_);
1924 void BufferView::message(docstring const & msg)
1927 d->gui_->message(msg);
1931 void BufferView::showDialog(string const & name)
1934 d->gui_->showDialog(name, string());
1938 void BufferView::showDialog(string const & name,
1939 string const & data, Inset * inset)
1942 d->gui_->showDialog(name, data, inset);
1946 void BufferView::updateDialog(string const & name, string const & data)
1949 d->gui_->updateDialog(name, data);
1953 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
1959 // FIXME: Move this out of BufferView again
1960 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
1962 if (!fname.isReadableFile()) {
1963 docstring const error = from_ascii(strerror(errno));
1964 docstring const file = makeDisplayPath(fname.absFilename(), 50);
1965 docstring const text =
1966 bformat(_("Could not read the specified document\n"
1967 "%1$s\ndue to the error: %2$s"), file, error);
1968 Alert::error(_("Could not read file"), text);
1972 if (!fname.isReadableFile()) {
1973 docstring const file = makeDisplayPath(fname.absFilename(), 50);
1974 docstring const text =
1975 bformat(_("%1$s\n is not readable."), file);
1976 Alert::error(_("Could not open file"), text);
1980 // FIXME UNICODE: We don't know the encoding of the file
1981 docstring file_content = fname.fileContents("UTF-8");
1982 if (file_content.empty()) {
1983 Alert::error(_("Reading not UTF-8 encoded file"),
1984 _("The file is not UTF-8 encoded.\n"
1985 "It will be read as local 8Bit-encoded.\n"
1986 "If this does not give the correct result\n"
1987 "then please change the encoding of the file\n"
1988 "to UTF-8 with a program other than LyX.\n"));
1989 file_content = fname.fileContents("local8bit");
1992 return normalize_c(file_content);
1996 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
1998 docstring const tmpstr = contentsOfPlaintextFile(f);
2003 Cursor & cur = cursor();
2004 cap::replaceSelection(cur);
2005 buffer_.undo().recordUndo(cur);
2007 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2009 cur.innerText()->insertStringAsLines(cur, tmpstr);