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"
24 #include "CutAndPaste.h"
26 #include "DispatchResult.h"
27 #include "ErrorList.h"
29 #include "FloatList.h"
30 #include "FuncRequest.h"
31 #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"
50 #include "TextClass.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/FileDialog.h"
63 #include "frontends/FontMetrics.h"
64 #include "frontends/Painter.h"
65 #include "frontends/Selection.h"
67 #include "graphics/Previews.h"
69 #include "support/convert.h"
70 #include "support/FileFilterList.h"
71 #include "support/filetools.h"
72 #include "support/Package.h"
73 #include "support/types.h"
74 #include "support/fs_extras.h"
76 #include <boost/bind.hpp>
77 #include <boost/current_function.hpp>
78 #include <boost/next_prior.hpp>
79 #include <boost/filesystem/operations.hpp>
89 using std::istringstream;
90 using std::istream_iterator;
94 using std::mem_fun_ref;
98 namespace fs = boost::filesystem;
102 using support::addPath;
103 using support::bformat;
104 using support::FileFilterList;
105 using support::FileName;
106 using support::fileSearch;
107 using support::isDirWriteable;
108 using support::isFileReadable;
109 using support::makeDisplayPath;
110 using support::makeAbsPath;
111 using support::package;
113 namespace Alert = frontend::Alert;
117 /// Return an inset of this class if it exists at the current cursor position
119 T * getInsetByCode(Cursor const & cur, Inset::Code code)
121 DocIterator it = cur;
122 Inset * inset = it.nextInset();
123 if (inset && inset->lyxCode() == code)
124 return static_cast<T*>(inset);
129 bool findInset(DocIterator & dit, vector<Inset_code> const & codes,
132 bool findNextInset(DocIterator & dit, vector<Inset_code> const & codes,
133 string const & contents)
135 DocIterator tmpdit = dit;
138 Inset const * inset = tmpdit.nextInset();
140 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
141 && (contents.empty() ||
142 static_cast<InsetCommand const *>(inset)->getContents() == contents)) {
146 tmpdit.forwardInset();
153 /// Looks for next inset with one of the the given code
154 bool findInset(DocIterator & dit, vector<Inset_code> const & codes,
158 DocIterator tmpdit = dit;
159 tmpdit.forwardInset();
164 Inset const * inset = tmpdit.nextInset();
166 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
167 contents = static_cast<InsetCommand const *>(inset)->getContents();
171 if (!findNextInset(tmpdit, codes, contents)) {
172 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
173 tmpdit = doc_iterator_begin(tmpdit.bottom().inset());
174 if (!findNextInset(tmpdit, codes, contents))
185 /// Looks for next inset with the given code
186 void findInset(DocIterator & dit, Inset_code code, bool same_content)
188 findInset(dit, vector<Inset_code>(1, code), same_content);
192 /// Moves cursor to the next inset with one of the given codes.
193 void gotoInset(BufferView * bv, vector<Inset_code> const & codes,
196 Cursor tmpcur = bv->cursor();
197 if (!findInset(tmpcur, codes, same_content)) {
198 bv->cursor().message(_("No more insets"));
202 tmpcur.clearSelection();
203 bv->setCursor(tmpcur);
207 /// Moves cursor to the next inset with given code.
208 void gotoInset(BufferView * bv, Inset_code code, bool same_content)
210 gotoInset(bv, vector<Inset_code>(1, code), same_content);
215 /// the type of outline operation
217 OutlineUp, // Move this header with text down
218 OutlineDown, // Move this header with text up
219 OutlineIn, // Make this header deeper
220 OutlineOut // Make this header shallower
224 void outline(OutlineOp mode, Cursor & cur)
226 Buffer & buf = cur.buffer();
227 pit_type & pit = cur.pit();
228 ParagraphList & pars = buf.text().paragraphs();
229 ParagraphList::iterator bgn = pars.begin();
230 // The first paragraph of the area to be copied:
231 ParagraphList::iterator start = boost::next(bgn, pit);
232 // The final paragraph of area to be copied:
233 ParagraphList::iterator finish = start;
234 ParagraphList::iterator end = pars.end();
236 TextClass::const_iterator lit =
237 buf.params().getTextClass().begin();
238 TextClass::const_iterator const lend =
239 buf.params().getTextClass().end();
241 int const thistoclevel = start->layout()->toclevel;
245 // Move out (down) from this section header
248 // Seek the one (on same level) below
249 for (; finish != end; ++finish) {
250 toclevel = finish->layout()->toclevel;
251 if (toclevel != Layout::NOT_IN_TOC
252 && toclevel <= thistoclevel) {
256 ParagraphList::iterator dest = start;
257 // Move out (up) from this header
260 // Search previous same-level header above
263 toclevel = dest->layout()->toclevel;
265 && (toclevel == Layout::NOT_IN_TOC
266 || toclevel > thistoclevel));
267 // Not found; do nothing
268 if (toclevel == Layout::NOT_IN_TOC || toclevel > thistoclevel)
270 pit_type const newpit = std::distance(bgn, dest);
271 pit_type const len = std::distance(start, finish);
272 pit_type const deletepit = pit + len;
273 recordUndo(cur, Undo::ATOMIC, newpit, deletepit - 1);
274 pars.insert(dest, start, finish);
275 start = boost::next(pars.begin(), deletepit);
277 pars.erase(start, finish);
281 // Go down out of current header:
284 // Find next same-level header:
285 for (; finish != end; ++finish) {
286 toclevel = finish->layout()->toclevel;
287 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
290 ParagraphList::iterator dest = finish;
291 // Go one down from *this* header:
296 // Go further down to find header to insert in front of:
297 for (; dest != end; ++dest) {
298 toclevel = dest->layout()->toclevel;
299 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
302 // One such was found:
303 pit_type newpit = std::distance(bgn, dest);
304 pit_type const len = std::distance(start, finish);
305 recordUndo(cur, Undo::ATOMIC, pit, newpit - 1);
306 pars.insert(dest, start, finish);
307 start = boost::next(bgn, pit);
309 pars.erase(start, finish);
314 for (; lit != lend; ++lit) {
315 if ((*lit)->toclevel == thistoclevel + 1 &&
316 start->layout()->labeltype == (*lit)->labeltype) {
317 start->layout((*lit));
324 for (; lit != lend; ++lit) {
325 if ((*lit)->toclevel == thistoclevel - 1 &&
326 start->layout()->labeltype == (*lit)->labeltype) {
327 start->layout((*lit));
340 /////////////////////////////////////////////////////////////////////
344 /////////////////////////////////////////////////////////////////////
347 BufferView::BufferView(Buffer & buf)
348 : width_(0), height_(0), buffer_(buf), wh_(0),
350 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
351 need_centering_(false), intl_(new Intl), last_inset_(0),
354 xsel_cache_.set = false;
355 intl_->initKeyMapper(lyxrc.use_kbmap);
357 cursor_.push(buffer_.inset());
358 cursor_.resetAnchor();
359 cursor_.setCurrentFont();
361 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
362 graphics::Previews::get().generateBufferPreviews(buffer_);
366 BufferView::~BufferView()
368 // current buffer is going to be switched-off, save cursor pos
369 // Ideally, the whole cursor stack should be saved, but session
370 // currently can only handle bottom (whole document) level pit and pos.
371 // That is to say, if a cursor is in a nested inset, it will be
372 // restore to the left of the top level inset.
373 LyX::ref().session().lastFilePos().save(
374 support::FileName(buffer_.fileName()),
375 boost::tie(cursor_.bottom().pit(), cursor_.bottom().pos()) );
379 Buffer & BufferView::buffer()
385 Buffer const & BufferView::buffer() const
391 bool BufferView::fitCursor()
393 if (cursorStatus(cursor_) == CUR_INSIDE) {
394 frontend::FontMetrics const & fm =
395 theFontMetrics(cursor_.getFont());
396 int const asc = fm.maxAscent();
397 int const des = fm.maxDescent();
398 Point const p = getPos(cursor_, cursor_.boundary());
399 if (p.y_ - asc >= 0 && p.y_ + des < height_)
407 bool BufferView::multiParSel()
409 if (!cursor_.selection())
411 bool ret = multiparsel_cache_;
412 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
413 // Either this, or previous selection spans paragraphs
414 return ret || multiparsel_cache_;
418 bool BufferView::update(Update::flags flags)
420 // last_inset_ points to the last visited inset. This pointer may become
421 // invalid because of keyboard editing. Since all such operations
422 // causes screen update(), I reset last_inset_ to avoid such a problem.
424 // This is close to a hot-path.
426 << BOOST_CURRENT_FUNCTION
427 << "[fitcursor = " << (flags & Update::FitCursor)
428 << ", forceupdate = " << (flags & Update::Force)
429 << ", singlepar = " << (flags & Update::SinglePar)
430 << "] buffer: " << &buffer_ << endl;
432 // Update macro store
433 if (!(cursor().inMathed() && cursor().inMacroMode()))
434 buffer_.buildMacros();
436 // Now do the first drawing step if needed. This consists on updating
437 // the CoordCache in updateMetrics().
438 // The second drawing step is done in WorkArea::redraw() if needed.
440 // Case when no explicit update is requested.
442 // no need to redraw anything.
443 metrics_info_.update_strategy = NoScreenUpdate;
447 if (flags == Update::Decoration) {
448 metrics_info_.update_strategy = DecorationUpdate;
452 if (flags == Update::FitCursor
453 || flags == (Update::Decoration | Update::FitCursor)) {
454 bool const fit_cursor = fitCursor();
455 // tell the frontend to update the screen if needed.
457 updateMetrics(false);
460 if (flags & Update::Decoration) {
461 metrics_info_.update_strategy = DecorationUpdate;
464 // no screen update is needed.
465 metrics_info_.update_strategy = NoScreenUpdate;
469 bool full_metrics = flags & Update::Force;
470 if (flags & Update::MultiParSel)
471 full_metrics |= multiParSel();
473 bool const single_par = !full_metrics;
474 updateMetrics(single_par);
476 if (flags & Update::FitCursor) {
477 //FIXME: updateMetrics() does not update paragraph position
478 // This is done at draw() time. So we need a redraw!
481 updateMetrics(false);
483 // The screen has already been updated thanks to the
484 // 'buffer_.changed()' call three line above. So no need
489 // tell the frontend to update the screen.
494 void BufferView::updateScrollbar()
496 Text & t = buffer_.text();
497 TextMetrics & tm = text_metrics_[&t];
499 int const parsize = int(t.paragraphs().size() - 1);
500 if (anchor_ref_ > parsize) {
501 anchor_ref_ = parsize;
506 << BOOST_CURRENT_FUNCTION
507 << " Updating scrollbar: height: " << t.paragraphs().size()
508 << " curr par: " << cursor_.bottom().pit()
509 << " default height " << defaultRowHeight() << endl;
511 // It would be better to fix the scrollbar to understand
512 // values in [0..1] and divide everything by wh
514 // estimated average paragraph height:
518 int h = tm.parMetrics(anchor_ref_).height();
520 // Normalize anchor/offset (MV):
521 while (offset_ref_ > h && anchor_ref_ < parsize) {
524 h = tm.parMetrics(anchor_ref_).height();
526 // Look at paragraph heights on-screen
529 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
532 int const h2 = tm.parMetrics(pit).height();
538 int const hav = sumh / nh;
539 // More realistic average paragraph height
544 scrollbarParameters_.height = (parsize + 1) * wh_;
545 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
546 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
550 ScrollbarParameters const & BufferView::scrollbarParameters() const
552 return scrollbarParameters_;
556 void BufferView::scrollDocView(int value)
558 LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
559 << "[ value = " << value << "]" << endl;
561 Text & t = buffer_.text();
562 TextMetrics & tm = text_metrics_[&t];
564 float const bar = value / float(wh_ * t.paragraphs().size());
566 anchor_ref_ = int(bar * t.paragraphs().size());
567 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
568 anchor_ref_ = int(t.paragraphs().size()) - 1;
570 tm.redoParagraph(anchor_ref_);
571 int const h = tm.parMetrics(anchor_ref_).height();
572 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
573 updateMetrics(false);
578 void BufferView::setCursorFromScrollbar()
580 TextMetrics & tm = text_metrics_[&buffer_.text()];
582 int const height = 2 * defaultRowHeight();
583 int const first = height;
584 int const last = height_ - height;
585 Cursor & cur = cursor_;
587 switch (cursorStatus(cur)) {
589 // We reset the cursor because cursorStatus() does not
590 // work when the cursor is within mathed.
591 cur.reset(buffer_.inset());
592 tm.setCursorFromCoordinates(cur, 0, first);
593 cur.clearSelection();
596 // We reset the cursor because cursorStatus() does not
597 // work when the cursor is within mathed.
598 cur.reset(buffer_.inset());
599 tm.setCursorFromCoordinates(cur, 0, last);
600 cur.clearSelection();
603 int const y = getPos(cur, cur.boundary()).y_;
604 int const newy = min(last, max(y, first));
606 cur.reset(buffer_.inset());
607 tm.setCursorFromCoordinates(cur, 0, newy);
613 Change const BufferView::getCurrentChange() const
615 if (!cursor_.selection())
616 return Change(Change::UNCHANGED);
618 DocIterator dit = cursor_.selectionBegin();
619 return dit.paragraph().lookupChange(dit.pos());
623 // this could be used elsewhere as well?
624 // FIXME: This does not work within mathed!
625 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
627 Point const p = getPos(dit, dit.boundary());
630 if (p.y_ > workHeight())
636 void BufferView::saveBookmark(unsigned int idx)
638 // tenatively save bookmark, id and pos will be used to
639 // acturately locate a bookmark in a 'live' lyx session.
640 // pit and pos will be updated with bottom level pit/pos
642 LyX::ref().session().bookmarks().save(
643 FileName(buffer_.fileName()),
644 cursor_.bottom().pit(),
645 cursor_.bottom().pos(),
646 cursor_.paragraph().id(),
651 // emit message signal.
652 message(_("Save bookmark"));
656 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
657 int top_id, pos_type top_pos)
659 bool success = false;
662 cursor_.clearSelection();
664 // if a valid par_id is given, try it first
665 // This is the case for a 'live' bookmark when unique paragraph ID
666 // is used to track bookmarks.
668 ParIterator par = buffer_.getParFromID(top_id);
669 if (par != buffer_.par_iterator_end()) {
670 doc_it = makeDocIterator(par, min(par->size(), top_pos));
671 // Some slices of the iterator may not be
672 // reachable (e.g. closed collapsable inset)
673 // so the dociterator may need to be
674 // shortened. Otherwise, setCursor may crash
675 // lyx when the cursor can not be set to these
677 size_t const n = doc_it.depth();
678 for (size_t i = 0; i < n; ++i)
679 if (doc_it[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
687 // if top_id == 0, or searching through top_id failed
688 // This is the case for a 'restored' bookmark when only bottom
689 // (document level) pit was saved. Because of this, bookmark
690 // restoration is inaccurate. If a bookmark was within an inset,
691 // it will be restored to the left of the outmost inset that contains
693 if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
694 doc_it = doc_iterator_begin(buffer_.inset());
695 doc_it.pit() = bottom_pit;
696 doc_it.pos() = min(bottom_pos, doc_it.paragraph().size());
701 // Note: only bottom (document) level pit is set.
703 // set the current font.
704 cursor_.setCurrentFont();
705 // center the screen on this new position.
713 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
715 if (lyxrc.rtl_support) {
716 if (cursor_.real_current_font.isRightToLeft()) {
717 if (intl_->keymap == Intl::PRIMARY)
720 if (intl_->keymap == Intl::SECONDARY)
725 intl_->getTransManager().translateAndInsert(c, t, cur);
729 int BufferView::workWidth() const
735 void BufferView::updateOffsetRef()
737 // No need to update offset_ref_ in this case.
738 if (!need_centering_)
741 // We are not properly started yet, delay until resizing is
746 CursorSlice & bot = cursor_.bottom();
747 TextMetrics & tm = text_metrics_[bot.text()];
748 ParagraphMetrics const & pm = tm.parMetrics(bot.pit());
749 int y = coordOffset(cursor_, cursor_.boundary()).y_;
750 offset_ref_ = y + pm.ascent() - height_ / 2;
752 need_centering_ = false;
756 void BufferView::center()
758 anchor_ref_ = cursor_.bottom().pit();
759 need_centering_ = true;
763 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
767 Cursor & cur = cursor_;
769 switch (cmd.action) {
772 flag.enabled(!buffer_.undostack().empty());
775 flag.enabled(!buffer_.redostack().empty());
777 case LFUN_FILE_INSERT:
778 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
779 case LFUN_FILE_INSERT_PLAINTEXT:
780 case LFUN_BOOKMARK_SAVE:
781 // FIXME: Actually, these LFUNS should be moved to Text
782 flag.enabled(cur.inTexted());
784 case LFUN_FONT_STATE:
785 case LFUN_LABEL_INSERT:
786 case LFUN_PARAGRAPH_GOTO:
787 // FIXME handle non-trivially
788 case LFUN_OUTLINE_UP:
789 case LFUN_OUTLINE_DOWN:
790 case LFUN_OUTLINE_IN:
791 case LFUN_OUTLINE_OUT:
793 case LFUN_REFERENCE_NEXT:
795 case LFUN_WORD_REPLACE:
798 case LFUN_MARK_TOGGLE:
799 case LFUN_SCREEN_RECENTER:
800 case LFUN_BIBTEX_DATABASE_ADD:
801 case LFUN_BIBTEX_DATABASE_DEL:
802 case LFUN_WORDS_COUNT:
803 case LFUN_NEXT_INSET_TOGGLE:
807 case LFUN_LABEL_GOTO: {
808 flag.enabled(!cmd.argument().empty()
809 || getInsetByCode<InsetRef>(cur, Inset::REF_CODE));
813 case LFUN_CHANGES_TRACK:
815 flag.setOnOff(buffer_.params().trackChanges);
818 case LFUN_CHANGES_OUTPUT:
820 flag.setOnOff(buffer_.params().outputChanges);
823 case LFUN_CHANGES_MERGE:
824 case LFUN_CHANGE_NEXT:
825 case LFUN_ALL_CHANGES_ACCEPT:
826 case LFUN_ALL_CHANGES_REJECT:
827 // TODO: context-sensitive enabling of LFUNs
828 // In principle, these command should only be enabled if there
829 // is a change in the document. However, without proper
830 // optimizations, this will inevitably result in poor performance.
834 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
835 flag.setOnOff(buffer_.params().compressed);
840 case LFUN_SCREEN_DOWN:
844 // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
845 // everywhere else before this can enabled:
846 case LFUN_SCREEN_UP_SELECT:
847 case LFUN_SCREEN_DOWN_SELECT:
859 Update::flags BufferView::dispatch(FuncRequest const & cmd)
861 //lyxerr << BOOST_CURRENT_FUNCTION
862 // << [ cmd = " << cmd << "]" << endl;
864 // Make sure that the cached BufferView is correct.
865 LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
866 << " action[" << cmd.action << ']'
867 << " arg[" << to_utf8(cmd.argument()) << ']'
868 << " x[" << cmd.x << ']'
869 << " y[" << cmd.y << ']'
870 << " button[" << cmd.button() << ']'
873 Cursor & cur = cursor_;
874 // Default Update flags.
875 Update::flags updateFlags = Update::Force | Update::FitCursor;
877 switch (cmd.action) {
880 cur.message(_("Undo"));
881 cur.clearSelection();
882 if (!textUndo(*this)) {
883 cur.message(_("No further undo information"));
884 updateFlags = Update::None;
889 cur.message(_("Redo"));
890 cur.clearSelection();
891 if (!textRedo(*this)) {
892 cur.message(_("No further redo information"));
893 updateFlags = Update::None;
897 case LFUN_FILE_INSERT:
899 menuInsertLyXFile(to_utf8(cmd.argument()));
902 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
904 insertPlaintextFile(to_utf8(cmd.argument()), true);
907 case LFUN_FILE_INSERT_PLAINTEXT:
909 insertPlaintextFile(to_utf8(cmd.argument()), false);
912 case LFUN_FONT_STATE:
913 cur.message(cur.currentState());
916 case LFUN_BOOKMARK_SAVE:
917 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
920 case LFUN_LABEL_GOTO: {
921 docstring label = cmd.argument();
924 getInsetByCode<InsetRef>(cursor_,
927 label = inset->getParam("reference");
928 // persistent=false: use temp_bookmark
938 case LFUN_PARAGRAPH_GOTO: {
939 int const id = convert<int>(to_utf8(cmd.argument()));
941 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
942 b = theBufferList().next(b)) {
944 ParIterator par = b->getParFromID(id);
945 if (par == b->par_iterator_end()) {
947 << "No matching paragraph found! ["
948 << id << "]." << endl;
951 << "Paragraph " << par->id()
952 << " found in buffer `"
953 << b->fileName() << "'." << endl;
957 setCursor(makeDocIterator(par, 0));
959 // Switch to other buffer view and resend cmd
960 theLyXFunc().dispatch(FuncRequest(
961 LFUN_BUFFER_SWITCH, b->fileName()));
962 theLyXFunc().dispatch(cmd);
963 updateFlags = Update::None;
972 case LFUN_OUTLINE_UP:
973 outline(OutlineUp, cursor_);
974 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
975 updateLabels(buffer_);
977 case LFUN_OUTLINE_DOWN:
978 outline(OutlineDown, cursor_);
979 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
980 updateLabels(buffer_);
982 case LFUN_OUTLINE_IN:
983 outline(OutlineIn, cursor_);
984 updateLabels(buffer_);
986 case LFUN_OUTLINE_OUT:
987 outline(OutlineOut, cursor_);
988 updateLabels(buffer_);
992 gotoInset(this, Inset::NOTE_CODE, false);
995 case LFUN_REFERENCE_NEXT: {
996 vector<Inset_code> tmp;
997 tmp.push_back(Inset::LABEL_CODE);
998 tmp.push_back(Inset::REF_CODE);
999 gotoInset(this, tmp, true);
1003 case LFUN_CHANGES_TRACK:
1004 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1007 case LFUN_CHANGES_OUTPUT:
1008 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1009 if (buffer_.params().outputChanges) {
1010 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1011 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1012 LaTeXFeatures::isAvailable("xcolor");
1014 if (!dvipost && !xcolorsoul) {
1015 Alert::warning(_("Changes not shown in LaTeX output"),
1016 _("Changes will not be highlighted in LaTeX output, "
1017 "because neither dvipost nor xcolor/soul are installed.\n"
1018 "Please install these packages or redefine "
1019 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1020 } else if (!xcolorsoul) {
1021 Alert::warning(_("Changes not shown in LaTeX output"),
1022 _("Changes will not be highlighted in LaTeX output "
1023 "when using pdflatex, because xcolor and soul are not installed.\n"
1024 "Please install both packages or redefine "
1025 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1030 case LFUN_CHANGE_NEXT:
1031 findNextChange(this);
1034 case LFUN_CHANGES_MERGE:
1035 if (findNextChange(this))
1036 showDialog("changes");
1039 case LFUN_ALL_CHANGES_ACCEPT:
1040 // select complete document
1041 cursor_.reset(buffer_.inset());
1042 cursor_.selHandle(true);
1043 buffer_.text().cursorBottom(cursor_);
1044 // accept everything in a single step to support atomic undo
1045 buffer_.text().acceptOrRejectChanges(cursor_, Text::ACCEPT);
1048 case LFUN_ALL_CHANGES_REJECT:
1049 // select complete document
1050 cursor_.reset(buffer_.inset());
1051 cursor_.selHandle(true);
1052 buffer_.text().cursorBottom(cursor_);
1053 // reject everything in a single step to support atomic undo
1054 // Note: reject does not work recursively; the user may have to repeat the operation
1055 buffer_.text().acceptOrRejectChanges(cursor_, Text::REJECT);
1058 case LFUN_WORD_FIND:
1062 case LFUN_WORD_REPLACE: {
1063 bool has_deleted = false;
1064 if (cur.selection()) {
1065 DocIterator beg = cur.selectionBegin();
1066 DocIterator end = cur.selectionEnd();
1067 if (beg.pit() == end.pit()) {
1068 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1069 if (cur.paragraph().isDeleted(p))
1074 replace(this, cmd, has_deleted);
1079 cur.clearSelection();
1081 cur.message(from_utf8(N_("Mark off")));
1085 cur.clearSelection();
1088 cur.message(from_utf8(N_("Mark on")));
1091 case LFUN_MARK_TOGGLE:
1092 cur.clearSelection();
1095 cur.message(from_utf8(N_("Mark removed")));
1098 cur.message(from_utf8(N_("Mark set")));
1103 case LFUN_SCREEN_RECENTER:
1107 case LFUN_BIBTEX_DATABASE_ADD: {
1108 Cursor tmpcur = cursor_;
1109 findInset(tmpcur, Inset::BIBTEX_CODE, false);
1110 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1111 Inset::BIBTEX_CODE);
1113 if (inset->addDatabase(to_utf8(cmd.argument())))
1114 buffer_.updateBibfilesCache();
1119 case LFUN_BIBTEX_DATABASE_DEL: {
1120 Cursor tmpcur = cursor_;
1121 findInset(tmpcur, Inset::BIBTEX_CODE, false);
1122 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1123 Inset::BIBTEX_CODE);
1125 if (inset->delDatabase(to_utf8(cmd.argument())))
1126 buffer_.updateBibfilesCache();
1131 case LFUN_WORDS_COUNT: {
1132 DocIterator from, to;
1133 if (cur.selection()) {
1134 from = cur.selectionBegin();
1135 to = cur.selectionEnd();
1137 from = doc_iterator_begin(buffer_.inset());
1138 to = doc_iterator_end(buffer_.inset());
1140 int const count = countWords(from, to);
1143 if (cur.selection())
1144 message = bformat(_("%1$d words in selection."),
1147 message = bformat(_("%1$d words in document."),
1151 if (cur.selection())
1152 message = _("One word in selection.");
1154 message = _("One word in document.");
1157 Alert::information(_("Count words"), message);
1161 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1162 // turn compression on/off
1163 buffer_.params().compressed = !buffer_.params().compressed;
1166 case LFUN_NEXT_INSET_TOGGLE: {
1167 // this is the real function we want to invoke
1168 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1169 // if there is an inset at cursor, see whether it
1171 Inset * inset = cur.nextInset();
1173 if (inset->isActive()) {
1174 Cursor tmpcur = cur;
1175 tmpcur.pushLeft(*inset);
1176 inset->dispatch(tmpcur, tmpcmd);
1177 if (tmpcur.result().dispatched()) {
1180 } else if (inset->editable() == Inset::IS_EDITABLE) {
1181 inset->edit(cur, true);
1184 // if it did not work, try the underlying inset.
1185 if (!cur.result().dispatched())
1186 cur.dispatch(tmpcmd);
1188 if (cur.result().dispatched())
1189 cur.clearSelection();
1194 case LFUN_SCREEN_UP:
1195 case LFUN_SCREEN_DOWN: {
1196 Point p = getPos(cur, cur.boundary());
1197 if (p.y_ < 0 || p.y_ > height_) {
1198 // The cursor is off-screen so recenter before proceeding.
1200 updateMetrics(false);
1201 //FIXME: updateMetrics() does not update paragraph position
1202 // This is done at draw() time. So we need a redraw!
1204 p = getPos(cur, cur.boundary());
1206 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1207 cur.reset(buffer_.inset());
1208 text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1209 //FIXME: what to do with cur.x_target()?
1211 // The metrics are already up to date. see scroll()
1212 updateFlags = Update::None;
1216 case LFUN_SCREEN_UP_SELECT:
1217 case LFUN_SCREEN_DOWN_SELECT: {
1218 cur.selHandle(true);
1219 size_t initial_depth = cur.depth();
1220 Point const p = getPos(cur, cur.boundary());
1221 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1222 // FIXME: We need to verify if the cursor stayed within an inset...
1223 //cur.reset(buffer_.inset());
1224 text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1226 while (cur.depth() > initial_depth) {
1229 // FIXME: we need to do a redraw again because of the selection
1231 updateFlags = Update::Force | Update::FitCursor;
1236 updateFlags = Update::None;
1243 docstring const BufferView::requestSelection()
1245 Cursor & cur = cursor_;
1247 if (!cur.selection()) {
1248 xsel_cache_.set = false;
1252 if (!xsel_cache_.set ||
1253 cur.top() != xsel_cache_.cursor ||
1254 cur.anchor_.top() != xsel_cache_.anchor)
1256 xsel_cache_.cursor = cur.top();
1257 xsel_cache_.anchor = cur.anchor_.top();
1258 xsel_cache_.set = cur.selection();
1259 return cur.selectionAsString(false);
1265 void BufferView::clearSelection()
1267 cursor_.clearSelection();
1268 // Clear the selection buffer. Otherwise a subsequent
1269 // middle-mouse-button paste would use the selection buffer,
1270 // not the more current external selection.
1271 cap::clearSelection();
1272 xsel_cache_.set = false;
1273 // The buffer did not really change, but this causes the
1274 // redraw we need because we cleared the selection above.
1279 void BufferView::resize(int width, int height)
1281 // Update from work area
1285 updateMetrics(false);
1289 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1291 TextMetrics & tm = text_metrics_[&text];
1292 Inset * inset = tm.checkInsetHit(x, y);
1296 if (!inset->descendable())
1297 // No need to go further down if the inset is not
1301 size_t cell_number = inset->nargs();
1302 // Check all the inner cell.
1303 for (size_t i = 0; i != cell_number; ++i) {
1304 Text const * inner_text = inset->getText(i);
1307 Inset const * inset_deeper =
1308 getCoveringInset(*inner_text, x, y);
1310 return inset_deeper;
1318 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1320 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1322 // This is only called for mouse related events including
1323 // LFUN_FILE_OPEN generated by drag-and-drop.
1324 FuncRequest cmd = cmd0;
1327 cur.push(buffer_.inset());
1328 cur.selection() = cursor_.selection();
1330 // Either the inset under the cursor or the
1331 // surrounding Text will handle this event.
1333 // make sure we stay within the screen...
1334 cmd.y = min(max(cmd.y, -1), height_);
1336 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1338 // Get inset under mouse, if there is one.
1339 Inset const * covering_inset =
1340 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1341 if (covering_inset == last_inset_)
1342 // Same inset, no need to do anything...
1345 bool need_redraw = false;
1346 // const_cast because of setMouseHover().
1347 Inset * inset = const_cast<Inset *>(covering_inset);
1349 // Remove the hint on the last hovered inset (if any).
1350 need_redraw |= last_inset_->setMouseHover(false);
1352 // Highlighted the newly hovered inset (if any).
1353 need_redraw |= inset->setMouseHover(true);
1354 last_inset_ = inset;
1358 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1359 // not expose the button for redraw. We adjust here the metrics dimension
1360 // to enable a full redraw in any case as this is not costly.
1361 TextMetrics & tm = text_metrics_[&buffer_.text()];
1362 std::pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
1363 std::pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1364 int y1 = firstpm.second->position() - firstpm.second->ascent();
1365 int y2 = lastpm.second->position() + lastpm.second->descent();
1366 metrics_info_ = ViewMetricsInfo(firstpm.first, lastpm.first, y1, y2,
1367 FullScreenUpdate, buffer_.text().paragraphs().size());
1368 // Reinitialize anchor to first pit.
1369 anchor_ref_ = firstpm.first;
1371 LYXERR(Debug::PAINTING)
1372 << "Mouse hover detected at: (" << cmd.x << ", " << cmd.y << ")"
1373 << "\nTriggering redraw: y1: " << y1 << " y2: " << y2
1374 << " pit1: " << firstpm.first << " pit2: " << lastpm.first << endl;
1376 // This event (moving without mouse click) is not passed further.
1377 // This should be changed if it is further utilized.
1382 // Build temporary cursor.
1383 Inset * inset = text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1385 // Put anchor at the same position.
1388 // Try to dispatch to an non-editable inset near this position
1389 // via the temp cursor. If the inset wishes to change the real
1390 // cursor it has to do so explicitly by using
1391 // cur.bv().cursor() = cur; (or similar)
1393 inset->dispatch(cur, cmd);
1395 // Now dispatch to the temporary cursor. If the real cursor should
1396 // be modified, the inset's dispatch has to do so explicitly.
1397 if (!cur.result().dispatched())
1400 //Do we have a selection?
1401 theSelection().haveSelection(cursor().selection());
1403 // If the command has been dispatched,
1404 if (cur.result().dispatched()
1405 // an update is asked,
1406 && cur.result().update()
1407 // and redraw is needed,
1408 && update(cur.result().update()))
1409 // then trigger a redraw.
1414 void BufferView::scroll(int y)
1423 void BufferView::scrollDown(int offset)
1425 Text * text = &buffer_.text();
1426 TextMetrics & tm = text_metrics_[text];
1427 int ymax = height_ + offset;
1429 std::pair<pit_type, ParagraphMetrics const *> last = tm.last();
1430 int bottom_pos = last.second->position() + last.second->descent();
1431 if (last.first + 1 == int(text->paragraphs().size())) {
1432 if (bottom_pos <= height_)
1434 offset = min(offset, bottom_pos - height_);
1437 if (bottom_pos > ymax)
1439 tm.newParMetricsDown();
1441 offset_ref_ += offset;
1442 updateMetrics(false);
1447 void BufferView::scrollUp(int offset)
1449 Text * text = &buffer_.text();
1450 TextMetrics & tm = text_metrics_[text];
1451 int ymin = - offset;
1453 std::pair<pit_type, ParagraphMetrics const *> first = tm.first();
1454 int top_pos = first.second->position() - first.second->ascent();
1455 if (first.first == 0) {
1458 offset = min(offset, - top_pos);
1463 tm.newParMetricsUp();
1465 offset_ref_ -= offset;
1466 updateMetrics(false);
1471 void BufferView::setCursorFromRow(int row)
1476 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1478 cursor_.reset(buffer_.inset());
1480 buffer_.text().setCursor(cursor_, 0, 0);
1482 buffer_.text().setCursor(cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1486 void BufferView::gotoLabel(docstring const & label)
1488 for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1489 vector<docstring> labels;
1490 it->getLabelList(buffer_, labels);
1491 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1500 TextMetrics const & BufferView::textMetrics(Text const * t) const
1502 return const_cast<BufferView *>(this)->textMetrics(t);
1506 TextMetrics & BufferView::textMetrics(Text const * t)
1508 TextMetricsCache::iterator tmc_it = text_metrics_.find(t);
1509 if (tmc_it == text_metrics_.end()) {
1510 tmc_it = text_metrics_.insert(
1511 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1513 return tmc_it->second;
1517 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1520 return textMetrics(t).parMetrics(pit);
1524 int BufferView::workHeight() const
1530 void BufferView::setCursor(DocIterator const & dit)
1532 size_t const n = dit.depth();
1533 for (size_t i = 0; i < n; ++i)
1534 dit[i].inset().edit(cursor_, true);
1536 cursor_.setCursor(dit);
1537 cursor_.selection() = false;
1541 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1543 // Would be wrong to delete anything if we have a selection.
1544 if (cur.selection())
1547 bool need_anchor_change = false;
1548 bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1549 need_anchor_change);
1551 if (need_anchor_change)
1557 updateLabels(buffer_);
1559 updateMetrics(false);
1565 bool BufferView::mouseSetCursor(Cursor & cur)
1567 BOOST_ASSERT(&cur.bv() == this);
1569 // this event will clear selection so we save selection for
1570 // persistent selection
1571 cap::saveSelection(cursor());
1573 // Has the cursor just left the inset?
1574 bool badcursor = false;
1575 bool leftinset = (&cursor_.inset() != &cur.inset());
1577 badcursor = notifyCursorLeaves(cursor_, cur);
1579 // do the dEPM magic if needed
1580 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1581 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1582 // the leftinset bool would not be necessary (badcursor instead).
1583 bool update = leftinset;
1584 if (!badcursor && cursor_.inTexted())
1585 update |= checkDepm(cur, cursor_);
1587 // if the cursor was in an empty script inset and the new
1588 // position is in the nucleus of the inset, notifyCursorLeaves
1589 // will kill the script inset itself. So we check all the
1590 // elements of the cursor to make sure that they are correct.
1591 // For an example, see bug 2933:
1592 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1593 // The code below could maybe be moved to a DocIterator method.
1594 //lyxerr << "cur before " << cur <<std::endl;
1595 DocIterator dit(cur.inset());
1596 dit.push_back(cur.bottom());
1598 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1599 dit.push_back(cur[i]);
1602 //lyxerr << "5 cur after" << dit <<std::endl;
1604 cursor_.setCursor(dit);
1605 cursor_.boundary(cur.boundary());
1606 cursor_.clearSelection();
1612 void BufferView::putSelectionAt(DocIterator const & cur,
1613 int length, bool backwards)
1615 cursor_.clearSelection();
1621 cursor_.pos() += length;
1622 cursor_.setSelection(cursor_, -length);
1624 cursor_.setSelection(cursor_, length);
1629 Cursor & BufferView::cursor()
1635 Cursor const & BufferView::cursor() const
1641 pit_type BufferView::anchor_ref() const
1647 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1649 return metrics_info_;
1653 bool BufferView::singleParUpdate()
1655 Text & buftext = buffer_.text();
1656 pit_type const bottom_pit = cursor_.bottom().pit();
1657 TextMetrics & tm = textMetrics(&buftext);
1658 int old_height = tm.parMetrics(bottom_pit).height();
1660 // In Single Paragraph mode, rebreak only
1661 // the (main text, not inset!) paragraph containing the cursor.
1662 // (if this paragraph contains insets etc., rebreaking will
1663 // recursively descend)
1664 tm.redoParagraph(bottom_pit);
1665 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
1666 if (pm.height() != old_height)
1667 // Paragraph height has changed so we cannot proceed to
1668 // the singlePar optimisation.
1671 int y1 = pm.position() - pm.ascent();
1672 int y2 = pm.position() + pm.descent();
1673 metrics_info_ = ViewMetricsInfo(bottom_pit, bottom_pit, y1, y2,
1674 SingleParUpdate, buftext.paragraphs().size());
1675 LYXERR(Debug::PAINTING)
1676 << BOOST_CURRENT_FUNCTION
1679 << " pit: " << bottom_pit
1686 void BufferView::updateMetrics(bool singlepar)
1688 if (singlepar && singleParUpdate())
1689 // No need to update the full screen metrics.
1692 Text & buftext = buffer_.text();
1693 pit_type const npit = int(buftext.paragraphs().size());
1695 if (anchor_ref_ > int(npit - 1)) {
1696 anchor_ref_ = int(npit - 1);
1700 // Clear out the position cache in case of full screen redraw,
1701 coord_cache_.clear();
1703 // Clear out paragraph metrics to avoid having invalid metrics
1704 // in the cache from paragraphs not relayouted below
1705 // The complete text metrics will be redone.
1706 text_metrics_.clear();
1708 TextMetrics & tm = textMetrics(&buftext);
1710 pit_type const pit = anchor_ref_;
1714 // Rebreak anchor paragraph.
1715 tm.redoParagraph(pit);
1717 // Take care of anchor offset if case a recentering is needed.
1720 int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1722 // Redo paragraphs above anchor if necessary.
1724 while (y1 > 0 && pit1 > 0) {
1725 y1 -= tm.parMetrics(pit1).ascent();
1727 tm.redoParagraph(pit1);
1728 y1 -= tm.parMetrics(pit1).descent();
1731 // Take care of ascent of first line
1732 y1 -= tm.parMetrics(pit1).ascent();
1734 // Normalize anchor for next time
1738 // Grey at the beginning is ugly
1739 if (pit1 == 0 && y1 > 0) {
1745 // Redo paragraphs below the anchor if necessary.
1747 while (y2 < height_ && pit2 < int(npit) - 1) {
1748 y2 += tm.parMetrics(pit2).descent();
1750 tm.redoParagraph(pit2);
1751 y2 += tm.parMetrics(pit2).ascent();
1754 // Take care of descent of last line
1755 y2 += tm.parMetrics(pit2).descent();
1757 LYXERR(Debug::PAINTING)
1758 << BOOST_CURRENT_FUNCTION
1761 << " pit1: " << pit1
1762 << " pit2: " << pit2
1763 << " npit: " << npit
1767 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1768 FullScreenUpdate, npit);
1770 if (lyxerr.debugging(Debug::WORKAREA)) {
1771 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1772 coord_cache_.dump();
1777 void BufferView::menuInsertLyXFile(string const & filenm)
1779 BOOST_ASSERT(cursor_.inTexted());
1780 string filename = filenm;
1782 if (filename.empty()) {
1783 // Launch a file browser
1785 string initpath = lyxrc.document_path;
1786 string const trypath = buffer_.filePath();
1787 // If directory is writeable, use this as default.
1788 if (isDirWriteable(FileName(trypath)))
1792 FileDialog fileDlg(_("Select LyX document to insert"),
1794 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1795 make_pair(_("Examples|#E#e"),
1796 from_utf8(addPath(package().system_support().absFilename(),
1799 FileDialog::Result result =
1800 fileDlg.open(from_utf8(initpath),
1801 FileFilterList(_("LyX Documents (*.lyx)")),
1804 if (result.first == FileDialog::Later)
1808 filename = to_utf8(result.second);
1810 // check selected filename
1811 if (filename.empty()) {
1812 // emit message signal.
1813 message(_("Canceled."));
1818 // Get absolute path of file and add ".lyx"
1819 // to the filename if necessary
1820 filename = fileSearch(string(), filename, "lyx").absFilename();
1822 docstring const disp_fn = makeDisplayPath(filename);
1823 // emit message signal.
1824 message(bformat(_("Inserting document %1$s..."), disp_fn));
1827 Buffer buf("", false);
1828 if (lyx::loadLyXFile(&buf, FileName(filename))) {
1829 ErrorList & el = buffer_.errorList("Parse");
1830 // Copy the inserted document error list into the current buffer one.
1831 el = buf.errorList("Parse");
1832 recordUndo(cursor_);
1833 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1834 buf.params().getTextClassPtr(), el);
1835 res = _("Document %1$s inserted.");
1837 res = _("Could not insert document %1$s");
1839 // emit message signal.
1840 message(bformat(res, disp_fn));
1841 buffer_.errors("Parse");
1842 updateMetrics(false);
1846 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1852 // Addup contribution of nested insets, from inside to outside,
1853 // keeping the outer paragraph for a special handling below
1854 for (size_t i = dit.depth() - 1; i >= 1; --i) {
1855 CursorSlice const & sl = dit[i];
1859 // get relative position inside sl.inset()
1860 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
1862 // Make relative position inside of the edited inset relative to sl.inset()
1866 // In case of an RTL inset, the edited inset will be positioned to the left
1869 bool boundary_i = boundary && i + 1 == dit.depth();
1870 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
1875 // remember width for the case that sl.inset() is positioned in an RTL inset
1876 if (i && dit[i - 1].text()) {
1877 // If this Inset is inside a Text Inset, retrieve the Dimension
1878 // from the containing text instead of using Inset::dimension() which
1879 // might not be implemented.
1880 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
1881 // elimination of Inset::dim_ cache. This coordOffset() method needs
1882 // to be rewritten in light of the new design.
1883 Dimension const & dim = parMetrics(dit[i - 1].text(),
1884 dit[i - 1].pit()).insetDimension(&sl.inset());
1887 Dimension const dim = sl.inset().dimension(*this);
1891 //lyxerr << "Cursor::getPos, i: "
1892 // << i << " x: " << xx << " y: " << y << endl;
1895 // Add contribution of initial rows of outermost paragraph
1896 CursorSlice const & sl = dit[0];
1897 TextMetrics const & tm = textMetrics(sl.text());
1898 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
1899 BOOST_ASSERT(!pm.rows().empty());
1900 y -= pm.rows()[0].ascent();
1902 // FIXME: document this mess
1904 if (sl.pos() > 0 && dit.depth() == 1) {
1906 if (pos && boundary)
1908 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << std::endl;
1909 rend = pm.pos2row(pos);
1911 rend = pm.pos2row(sl.pos());
1913 size_t rend = pm.pos2row(sl.pos());
1915 for (size_t rit = 0; rit != rend; ++rit)
1916 y += pm.rows()[rit].height();
1917 y += pm.rows()[rend].ascent();
1919 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
1921 // Make relative position from the nested inset now bufferview absolute.
1922 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
1925 // In the RTL case place the nested inset at the left of the cursor in
1926 // the outer paragraph
1927 bool boundary_1 = boundary && 1 == dit.depth();
1928 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
1936 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
1938 CursorSlice const & bot = dit.bottom();
1939 TextMetrics const & tm = textMetrics(bot.text());
1940 if (!tm.has(bot.pit()))
1941 return Point(-1, -1);
1943 Point p = coordOffset(dit, boundary); // offset from outer paragraph
1944 p.y_ += tm.parMetrics(bot.pit()).position();
1949 void BufferView::draw(frontend::Painter & pain)
1951 PainterInfo pi(this, pain);
1952 // Should the whole screen, including insets, be refreshed?
1953 // FIXME: We should also distinguish DecorationUpdate to avoid text
1954 // drawing if possible. This is not possible to do easily right now
1955 // because of the single backing pixmap.
1956 pi.full_repaint = metrics_info_.update_strategy != SingleParUpdate;
1958 if (pi.full_repaint)
1959 // Clear background (if not delegated to rows)
1960 pain.fillRectangle(0, metrics_info_.y1, width_,
1961 metrics_info_.y2 - metrics_info_.y1,
1962 buffer_.inset().backgroundColor());
1964 LYXERR(Debug::PAINTING) << "\t\t*** START DRAWING ***" << endl;
1965 Text & text = buffer_.text();
1966 TextMetrics const & tm = text_metrics_[&text];
1967 int y = metrics_info_.y1 + tm.parMetrics(metrics_info_.p1).ascent();
1968 if (!pi.full_repaint)
1969 tm.drawParagraph(pi, metrics_info_.p1, 0, y);
1972 LYXERR(Debug::PAINTING) << "\n\t\t*** END DRAWING ***" << endl;
1974 // and grey out above (should not happen later)
1975 // lyxerr << "par ascent: " << text.getPar(metrics_info_.p1).ascent() << endl;
1976 if (metrics_info_.y1 > 0
1977 && metrics_info_.update_strategy == FullScreenUpdate)
1978 pain.fillRectangle(0, 0, width_, metrics_info_.y1, Color::bottomarea);
1980 // and possibly grey out below
1981 // lyxerr << "par descent: " << text.getPar(metrics_info_.p1).ascent() << endl;
1982 if (metrics_info_.y2 < height_
1983 && metrics_info_.update_strategy == FullScreenUpdate)
1984 pain.fillRectangle(0, metrics_info_.y2, width_,
1985 height_ - metrics_info_.y2, Color::bottomarea);
1989 void BufferView::message(docstring const & msg)
1996 void BufferView::showDialog(std::string const & name)
1999 gui_->showDialog(name);
2003 void BufferView::showDialogWithData(std::string const & name,
2004 std::string const & data)
2007 gui_->showDialogWithData(name, data);
2011 void BufferView::showInsetDialog(std::string const & name,
2012 std::string const & data, Inset * inset)
2015 gui_->showInsetDialog(name, data, inset);
2019 void BufferView::updateDialog(std::string const & name, std::string const & data)
2022 gui_->updateDialog(name, data);
2026 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2032 // FIXME: Move this out of BufferView again
2033 docstring BufferView::contentsOfPlaintextFile(string const & f,
2038 if (fname.empty()) {
2039 FileDialog fileDlg(_("Select file to insert"),
2041 ? LFUN_FILE_INSERT_PLAINTEXT_PARA
2042 : LFUN_FILE_INSERT_PLAINTEXT) );
2044 FileDialog::Result result =
2045 fileDlg.open(from_utf8(buffer().filePath()),
2046 FileFilterList(), docstring());
2048 if (result.first == FileDialog::Later)
2051 fname = makeAbsPath(to_utf8(result.second));
2057 if (!fs::is_readable(fname.toFilesystemEncoding())) {
2058 docstring const error = from_ascii(strerror(errno));
2059 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2060 docstring const text =
2061 bformat(_("Could not read the specified document\n"
2062 "%1$s\ndue to the error: %2$s"), file, error);
2063 Alert::error(_("Could not read file"), text);
2067 ifstream ifs(fname.toFilesystemEncoding().c_str());
2069 docstring const error = from_ascii(strerror(errno));
2070 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2071 docstring const text =
2072 bformat(_("Could not open the specified document\n"
2073 "%1$s\ndue to the error: %2$s"), file, error);
2074 Alert::error(_("Could not open file"), text);
2078 ifs.unsetf(std::ios::skipws);
2079 istream_iterator<char> ii(ifs);
2080 istream_iterator<char> end;
2081 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
2082 // We use this until the compilers get better...
2083 std::vector<char> tmp;
2084 copy(ii, end, back_inserter(tmp));
2085 string const tmpstr(tmp.begin(), tmp.end());
2087 // This is what we want to use and what we will use once the
2088 // compilers get good enough.
2089 //string tmpstr(ii, end); // yet a reason for using std::string
2090 // alternate approach to get the file into a string:
2092 copy(ii, end, back_inserter(tmpstr));
2095 // FIXME UNICODE: We don't know the encoding of the file
2096 docstring file_content = from_utf8(tmpstr);
2097 if (file_content.empty()) {
2098 Alert::error(_("Reading not UTF-8 encoded file"),
2099 _("The file is not UTF-8 encoded.\n"
2100 "It will be read as local 8Bit-encoded.\n"
2101 "If this does not give the correct result\n"
2102 "then please change the encoding of the file\n"
2103 "to UTF-8 with a program other than LyX.\n"));
2104 file_content = from_local8bit(tmpstr);
2107 return normalize_c(file_content);
2111 void BufferView::insertPlaintextFile(string const & f, bool asParagraph)
2113 docstring const tmpstr = contentsOfPlaintextFile(f, asParagraph);
2118 Cursor & cur = cursor();
2119 cap::replaceSelection(cur);
2122 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2124 cur.innerText()->insertStringAsLines(cur, tmpstr);