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 "callback.h" // added for Dispatch functions
24 #include "CoordCache.h"
25 #include "CutAndPaste.h"
27 #include "DispatchResult.h"
28 #include "ErrorList.h"
30 #include "FloatList.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
35 #include "InsetIterator.h"
37 #include "LaTeXFeatures.h"
43 #include "MetricsInfo.h"
44 #include "Paragraph.h"
45 #include "paragraph_funcs.h"
46 #include "ParagraphParameters.h"
47 #include "ParIterator.h"
51 #include "TextClass.h"
54 #include "WordLangTuple.h"
56 #include "insets/InsetBibtex.h"
57 #include "insets/InsetCommand.h" // ChangeRefs
58 #include "insets/InsetRef.h"
59 #include "insets/InsetText.h"
61 #include "frontends/alert.h"
62 #include "frontends/Delegates.h"
63 #include "frontends/FileDialog.h"
64 #include "frontends/FontMetrics.h"
65 #include "frontends/Painter.h"
66 #include "frontends/Selection.h"
68 #include "graphics/Previews.h"
70 #include "support/convert.h"
71 #include "support/FileFilterList.h"
72 #include "support/filetools.h"
73 #include "support/Package.h"
74 #include "support/types.h"
76 #include <boost/bind.hpp>
77 #include <boost/current_function.hpp>
78 #include <boost/next_prior.hpp>
85 using std::istringstream;
89 using std::mem_fun_ref;
96 using support::addPath;
97 using support::bformat;
98 using support::FileFilterList;
99 using support::FileName;
100 using support::fileSearch;
101 using support::isDirWriteable;
102 using support::isFileReadable;
103 using support::makeDisplayPath;
104 using support::package;
106 namespace Alert = frontend::Alert;
110 /// Return an inset of this class if it exists at the current cursor position
112 T * getInsetByCode(Cursor const & cur, Inset::Code code)
114 DocIterator it = cur;
115 Inset * inset = it.nextInset();
116 if (inset && inset->lyxCode() == code)
117 return static_cast<T*>(inset);
122 bool findInset(DocIterator & dit, vector<Inset_code> const & codes,
125 bool findNextInset(DocIterator & dit, vector<Inset_code> const & codes,
126 string const & contents)
128 DocIterator tmpdit = dit;
131 Inset const * inset = tmpdit.nextInset();
133 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
134 && (contents.empty() ||
135 static_cast<InsetCommand const *>(inset)->getContents() == contents)) {
139 tmpdit.forwardInset();
146 /// Looks for next inset with one of the the given code
147 bool findInset(DocIterator & dit, vector<Inset_code> const & codes,
151 DocIterator tmpdit = dit;
152 tmpdit.forwardInset();
157 Inset const * inset = tmpdit.nextInset();
159 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
160 contents = static_cast<InsetCommand const *>(inset)->getContents();
164 if (!findNextInset(tmpdit, codes, contents)) {
165 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
166 tmpdit = doc_iterator_begin(tmpdit.bottom().inset());
167 if (!findNextInset(tmpdit, codes, contents))
178 /// Looks for next inset with the given code
179 void findInset(DocIterator & dit, Inset_code code, bool same_content)
181 findInset(dit, vector<Inset_code>(1, code), same_content);
185 /// Moves cursor to the next inset with one of the given codes.
186 void gotoInset(BufferView * bv, vector<Inset_code> const & codes,
189 Cursor tmpcur = bv->cursor();
190 if (!findInset(tmpcur, codes, same_content)) {
191 bv->cursor().message(_("No more insets"));
195 tmpcur.clearSelection();
196 bv->setCursor(tmpcur);
200 /// Moves cursor to the next inset with given code.
201 void gotoInset(BufferView * bv, Inset_code code, bool same_content)
203 gotoInset(bv, vector<Inset_code>(1, code), same_content);
208 /// the type of outline operation
210 OutlineUp, // Move this header with text down
211 OutlineDown, // Move this header with text up
212 OutlineIn, // Make this header deeper
213 OutlineOut // Make this header shallower
217 void outline(OutlineOp mode, Cursor & cur)
219 Buffer & buf = cur.buffer();
220 pit_type & pit = cur.pit();
221 ParagraphList & pars = buf.text().paragraphs();
222 ParagraphList::iterator bgn = pars.begin();
223 // The first paragraph of the area to be copied:
224 ParagraphList::iterator start = boost::next(bgn, pit);
225 // The final paragraph of area to be copied:
226 ParagraphList::iterator finish = start;
227 ParagraphList::iterator end = pars.end();
229 TextClass::const_iterator lit =
230 buf.params().getTextClass().begin();
231 TextClass::const_iterator const lend =
232 buf.params().getTextClass().end();
234 int const thistoclevel = start->layout()->toclevel;
238 // Move out (down) from this section header
241 // Seek the one (on same level) below
242 for (; finish != end; ++finish) {
243 toclevel = finish->layout()->toclevel;
244 if (toclevel != Layout::NOT_IN_TOC
245 && toclevel <= thistoclevel) {
249 ParagraphList::iterator dest = start;
250 // Move out (up) from this header
253 // Search previous same-level header above
256 toclevel = dest->layout()->toclevel;
258 && (toclevel == Layout::NOT_IN_TOC
259 || toclevel > thistoclevel));
260 // Not found; do nothing
261 if (toclevel == Layout::NOT_IN_TOC || toclevel > thistoclevel)
263 pit_type const newpit = std::distance(bgn, dest);
264 pit_type const len = std::distance(start, finish);
265 pit_type const deletepit = pit + len;
266 recordUndo(cur, Undo::ATOMIC, newpit, deletepit - 1);
267 pars.insert(dest, start, finish);
268 start = boost::next(pars.begin(), deletepit);
270 pars.erase(start, finish);
274 // Go down out of current header:
277 // Find next same-level header:
278 for (; finish != end; ++finish) {
279 toclevel = finish->layout()->toclevel;
280 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
283 ParagraphList::iterator dest = finish;
284 // Go one down from *this* header:
289 // Go further down to find header to insert in front of:
290 for (; dest != end; ++dest) {
291 toclevel = dest->layout()->toclevel;
292 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
295 // One such was found:
296 pit_type newpit = std::distance(bgn, dest);
297 pit_type const len = std::distance(start, finish);
298 recordUndo(cur, Undo::ATOMIC, pit, newpit - 1);
299 pars.insert(dest, start, finish);
300 start = boost::next(bgn, pit);
302 pars.erase(start, finish);
307 for (; lit != lend; ++lit) {
308 if ((*lit)->toclevel == thistoclevel + 1 &&
309 start->layout()->labeltype == (*lit)->labeltype) {
310 start->layout((*lit));
317 for (; lit != lend; ++lit) {
318 if ((*lit)->toclevel == thistoclevel - 1 &&
319 start->layout()->labeltype == (*lit)->labeltype) {
320 start->layout((*lit));
333 /////////////////////////////////////////////////////////////////////
337 /////////////////////////////////////////////////////////////////////
340 BufferView::BufferView(Buffer & buf)
341 : width_(0), height_(0), buffer_(buf), wh_(0),
343 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
344 need_centering_(false), intl_(new Intl), last_inset_(0),
347 xsel_cache_.set = false;
348 intl_->initKeyMapper(lyxrc.use_kbmap);
350 cursor_.push(buffer_.inset());
351 cursor_.resetAnchor();
352 cursor_.setCurrentFont();
354 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
355 graphics::Previews::get().generateBufferPreviews(buffer_);
359 BufferView::~BufferView()
361 // current buffer is going to be switched-off, save cursor pos
362 // Ideally, the whole cursor stack should be saved, but session
363 // currently can only handle bottom (whole document) level pit and pos.
364 // That is to say, if a cursor is in a nested inset, it will be
365 // restore to the left of the top level inset.
366 LyX::ref().session().lastFilePos().save(
367 support::FileName(buffer_.fileName()),
368 boost::tie(cursor_.bottom().pit(), cursor_.bottom().pos()) );
372 Buffer & BufferView::buffer()
378 Buffer const & BufferView::buffer() const
384 bool BufferView::fitCursor()
386 if (cursorStatus(cursor_) == CUR_INSIDE) {
387 frontend::FontMetrics const & fm =
388 theFontMetrics(cursor_.getFont());
389 int const asc = fm.maxAscent();
390 int const des = fm.maxDescent();
391 Point const p = getPos(cursor_, cursor_.boundary());
392 if (p.y_ - asc >= 0 && p.y_ + des < height_)
400 bool BufferView::multiParSel()
402 if (!cursor_.selection())
404 bool ret = multiparsel_cache_;
405 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
406 // Either this, or previous selection spans paragraphs
407 return ret || multiparsel_cache_;
411 bool BufferView::update(Update::flags flags)
413 // last_inset_ points to the last visited inset. This pointer may become
414 // invalid because of keyboard editing. Since all such operations
415 // causes screen update(), I reset last_inset_ to avoid such a problem.
417 // This is close to a hot-path.
419 << BOOST_CURRENT_FUNCTION
420 << "[fitcursor = " << (flags & Update::FitCursor)
421 << ", forceupdate = " << (flags & Update::Force)
422 << ", singlepar = " << (flags & Update::SinglePar)
423 << "] buffer: " << &buffer_ << endl;
425 // Update macro store
426 if (!(cursor().inMathed() && cursor().inMacroMode()))
427 buffer_.buildMacros();
429 // Now do the first drawing step if needed. This consists on updating
430 // the CoordCache in updateMetrics().
431 // The second drawing step is done in WorkArea::redraw() if needed.
433 // Case when no explicit update is requested.
435 // no need to redraw anything.
436 metrics_info_.update_strategy = NoScreenUpdate;
440 if (flags == Update::Decoration) {
441 metrics_info_.update_strategy = DecorationUpdate;
445 if (flags == Update::FitCursor
446 || flags == (Update::Decoration | Update::FitCursor)) {
447 bool const fit_cursor = fitCursor();
448 // tell the frontend to update the screen if needed.
450 updateMetrics(false);
453 if (flags & Update::Decoration) {
454 metrics_info_.update_strategy = DecorationUpdate;
457 // no screen update is needed.
458 metrics_info_.update_strategy = NoScreenUpdate;
462 bool full_metrics = flags & Update::Force;
463 if (flags & Update::MultiParSel)
464 full_metrics |= multiParSel();
466 bool const single_par = !full_metrics;
467 updateMetrics(single_par);
469 if (flags & Update::FitCursor) {
470 //FIXME: updateMetrics() does not update paragraph position
471 // This is done at draw() time. So we need a redraw!
474 updateMetrics(false);
476 // The screen has already been updated thanks to the
477 // 'buffer_.changed()' call three line above. So no need
482 // tell the frontend to update the screen.
487 void BufferView::updateScrollbar()
489 Text & t = buffer_.text();
490 TextMetrics & tm = text_metrics_[&t];
492 int const parsize = int(t.paragraphs().size() - 1);
493 if (anchor_ref_ > parsize) {
494 anchor_ref_ = parsize;
499 << BOOST_CURRENT_FUNCTION
500 << " Updating scrollbar: height: " << t.paragraphs().size()
501 << " curr par: " << cursor_.bottom().pit()
502 << " default height " << defaultRowHeight() << endl;
504 // It would be better to fix the scrollbar to understand
505 // values in [0..1] and divide everything by wh
507 // estimated average paragraph height:
511 int h = tm.parMetrics(anchor_ref_).height();
513 // Normalize anchor/offset (MV):
514 while (offset_ref_ > h && anchor_ref_ < parsize) {
517 h = tm.parMetrics(anchor_ref_).height();
519 // Look at paragraph heights on-screen
522 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
525 int const h2 = tm.parMetrics(pit).height();
531 int const hav = sumh / nh;
532 // More realistic average paragraph height
537 scrollbarParameters_.height = (parsize + 1) * wh_;
538 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
539 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
543 ScrollbarParameters const & BufferView::scrollbarParameters() const
545 return scrollbarParameters_;
549 void BufferView::scrollDocView(int value)
551 LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
552 << "[ value = " << value << "]" << endl;
554 Text & t = buffer_.text();
555 TextMetrics & tm = text_metrics_[&t];
557 float const bar = value / float(wh_ * t.paragraphs().size());
559 anchor_ref_ = int(bar * t.paragraphs().size());
560 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
561 anchor_ref_ = int(t.paragraphs().size()) - 1;
563 tm.redoParagraph(anchor_ref_);
564 int const h = tm.parMetrics(anchor_ref_).height();
565 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
566 updateMetrics(false);
571 void BufferView::setCursorFromScrollbar()
573 TextMetrics & tm = text_metrics_[&buffer_.text()];
575 int const height = 2 * defaultRowHeight();
576 int const first = height;
577 int const last = height_ - height;
578 Cursor & cur = cursor_;
580 switch (cursorStatus(cur)) {
582 // We reset the cursor because cursorStatus() does not
583 // work when the cursor is within mathed.
584 cur.reset(buffer_.inset());
585 tm.setCursorFromCoordinates(cur, 0, first);
586 cur.clearSelection();
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, last);
593 cur.clearSelection();
596 int const y = getPos(cur, cur.boundary()).y_;
597 int const newy = min(last, max(y, first));
599 cur.reset(buffer_.inset());
600 tm.setCursorFromCoordinates(cur, 0, newy);
606 Change const BufferView::getCurrentChange() const
608 if (!cursor_.selection())
609 return Change(Change::UNCHANGED);
611 DocIterator dit = cursor_.selectionBegin();
612 return dit.paragraph().lookupChange(dit.pos());
616 // this could be used elsewhere as well?
617 // FIXME: This does not work within mathed!
618 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
620 Point const p = getPos(dit, dit.boundary());
623 if (p.y_ > workHeight())
629 void BufferView::saveBookmark(unsigned int idx)
631 // tenatively save bookmark, id and pos will be used to
632 // acturately locate a bookmark in a 'live' lyx session.
633 // pit and pos will be updated with bottom level pit/pos
635 LyX::ref().session().bookmarks().save(
636 FileName(buffer_.fileName()),
637 cursor_.bottom().pit(),
638 cursor_.bottom().pos(),
639 cursor_.paragraph().id(),
644 // emit message signal.
645 message(_("Save bookmark"));
649 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
650 int top_id, pos_type top_pos)
652 bool success = false;
655 cursor_.clearSelection();
657 // if a valid par_id is given, try it first
658 // This is the case for a 'live' bookmark when unique paragraph ID
659 // is used to track bookmarks.
661 ParIterator par = buffer_.getParFromID(top_id);
662 if (par != buffer_.par_iterator_end()) {
663 doc_it = makeDocIterator(par, min(par->size(), top_pos));
664 // Some slices of the iterator may not be
665 // reachable (e.g. closed collapsable inset)
666 // so the dociterator may need to be
667 // shortened. Otherwise, setCursor may crash
668 // lyx when the cursor can not be set to these
670 size_t const n = doc_it.depth();
671 for (size_t i = 0; i < n; ++i)
672 if (doc_it[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
680 // if top_id == 0, or searching through top_id failed
681 // This is the case for a 'restored' bookmark when only bottom
682 // (document level) pit was saved. Because of this, bookmark
683 // restoration is inaccurate. If a bookmark was within an inset,
684 // it will be restored to the left of the outmost inset that contains
686 if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
687 doc_it = doc_iterator_begin(buffer_.inset());
688 doc_it.pit() = bottom_pit;
689 doc_it.pos() = min(bottom_pos, doc_it.paragraph().size());
694 // Note: only bottom (document) level pit is set.
696 // set the current font.
697 cursor_.setCurrentFont();
698 // center the screen on this new position.
706 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
708 if (lyxrc.rtl_support) {
709 if (cursor_.real_current_font.isRightToLeft()) {
710 if (intl_->keymap == Intl::PRIMARY)
713 if (intl_->keymap == Intl::SECONDARY)
718 intl_->getTransManager().translateAndInsert(c, t, cur);
722 int BufferView::workWidth() const
728 void BufferView::updateOffsetRef()
730 // No need to update offset_ref_ in this case.
731 if (!need_centering_)
734 // We are not properly started yet, delay until resizing is
739 CursorSlice & bot = cursor_.bottom();
740 TextMetrics & tm = text_metrics_[bot.text()];
741 ParagraphMetrics const & pm = tm.parMetrics(bot.pit());
742 int y = coordOffset(cursor_, cursor_.boundary()).y_;
743 offset_ref_ = y + pm.ascent() - height_ / 2;
745 need_centering_ = false;
749 void BufferView::center()
751 anchor_ref_ = cursor_.bottom().pit();
752 need_centering_ = true;
756 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
760 Cursor & cur = cursor_;
762 switch (cmd.action) {
765 flag.enabled(!buffer_.undostack().empty());
768 flag.enabled(!buffer_.redostack().empty());
770 case LFUN_FILE_INSERT:
771 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
772 case LFUN_FILE_INSERT_PLAINTEXT:
773 case LFUN_BOOKMARK_SAVE:
774 // FIXME: Actually, these LFUNS should be moved to Text
775 flag.enabled(cur.inTexted());
777 case LFUN_FONT_STATE:
778 case LFUN_LABEL_INSERT:
779 case LFUN_PARAGRAPH_GOTO:
780 // FIXME handle non-trivially
781 case LFUN_OUTLINE_UP:
782 case LFUN_OUTLINE_DOWN:
783 case LFUN_OUTLINE_IN:
784 case LFUN_OUTLINE_OUT:
786 case LFUN_REFERENCE_NEXT:
788 case LFUN_WORD_REPLACE:
791 case LFUN_MARK_TOGGLE:
792 case LFUN_SCREEN_RECENTER:
793 case LFUN_BIBTEX_DATABASE_ADD:
794 case LFUN_BIBTEX_DATABASE_DEL:
795 case LFUN_WORDS_COUNT:
796 case LFUN_NEXT_INSET_TOGGLE:
800 case LFUN_LABEL_GOTO: {
801 flag.enabled(!cmd.argument().empty()
802 || getInsetByCode<InsetRef>(cur, Inset::REF_CODE));
806 case LFUN_CHANGES_TRACK:
808 flag.setOnOff(buffer_.params().trackChanges);
811 case LFUN_CHANGES_OUTPUT:
813 flag.setOnOff(buffer_.params().outputChanges);
816 case LFUN_CHANGES_MERGE:
817 case LFUN_CHANGE_NEXT:
818 case LFUN_ALL_CHANGES_ACCEPT:
819 case LFUN_ALL_CHANGES_REJECT:
820 // TODO: context-sensitive enabling of LFUNs
821 // In principle, these command should only be enabled if there
822 // is a change in the document. However, without proper
823 // optimizations, this will inevitably result in poor performance.
827 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
828 flag.setOnOff(buffer_.params().compressed);
833 case LFUN_SCREEN_DOWN:
837 // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
838 // everywhere else before this can enabled:
839 case LFUN_SCREEN_UP_SELECT:
840 case LFUN_SCREEN_DOWN_SELECT:
852 Update::flags BufferView::dispatch(FuncRequest const & cmd)
854 //lyxerr << BOOST_CURRENT_FUNCTION
855 // << [ cmd = " << cmd << "]" << endl;
857 // Make sure that the cached BufferView is correct.
858 LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
859 << " action[" << cmd.action << ']'
860 << " arg[" << to_utf8(cmd.argument()) << ']'
861 << " x[" << cmd.x << ']'
862 << " y[" << cmd.y << ']'
863 << " button[" << cmd.button() << ']'
866 Cursor & cur = cursor_;
867 // Default Update flags.
868 Update::flags updateFlags = Update::Force | Update::FitCursor;
870 switch (cmd.action) {
873 cur.message(_("Undo"));
874 cur.clearSelection();
875 if (!textUndo(*this)) {
876 cur.message(_("No further undo information"));
877 updateFlags = Update::None;
882 cur.message(_("Redo"));
883 cur.clearSelection();
884 if (!textRedo(*this)) {
885 cur.message(_("No further redo information"));
886 updateFlags = Update::None;
890 case LFUN_FILE_INSERT:
892 menuInsertLyXFile(to_utf8(cmd.argument()));
895 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
897 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
900 case LFUN_FILE_INSERT_PLAINTEXT:
902 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
905 case LFUN_FONT_STATE:
906 cur.message(cur.currentState());
909 case LFUN_BOOKMARK_SAVE:
910 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
913 case LFUN_LABEL_GOTO: {
914 docstring label = cmd.argument();
917 getInsetByCode<InsetRef>(cursor_,
920 label = inset->getParam("reference");
921 // persistent=false: use temp_bookmark
931 case LFUN_PARAGRAPH_GOTO: {
932 int const id = convert<int>(to_utf8(cmd.argument()));
934 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
935 b = theBufferList().next(b)) {
937 ParIterator par = b->getParFromID(id);
938 if (par == b->par_iterator_end()) {
940 << "No matching paragraph found! ["
941 << id << "]." << endl;
944 << "Paragraph " << par->id()
945 << " found in buffer `"
946 << b->fileName() << "'." << endl;
950 setCursor(makeDocIterator(par, 0));
952 // Switch to other buffer view and resend cmd
953 theLyXFunc().dispatch(FuncRequest(
954 LFUN_BUFFER_SWITCH, b->fileName()));
955 theLyXFunc().dispatch(cmd);
956 updateFlags = Update::None;
965 case LFUN_OUTLINE_UP:
966 outline(OutlineUp, cursor_);
967 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
968 updateLabels(buffer_);
970 case LFUN_OUTLINE_DOWN:
971 outline(OutlineDown, cursor_);
972 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
973 updateLabels(buffer_);
975 case LFUN_OUTLINE_IN:
976 outline(OutlineIn, cursor_);
977 updateLabels(buffer_);
979 case LFUN_OUTLINE_OUT:
980 outline(OutlineOut, cursor_);
981 updateLabels(buffer_);
985 gotoInset(this, Inset::NOTE_CODE, false);
988 case LFUN_REFERENCE_NEXT: {
989 vector<Inset_code> tmp;
990 tmp.push_back(Inset::LABEL_CODE);
991 tmp.push_back(Inset::REF_CODE);
992 gotoInset(this, tmp, true);
996 case LFUN_CHANGES_TRACK:
997 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1000 case LFUN_CHANGES_OUTPUT:
1001 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1002 if (buffer_.params().outputChanges) {
1003 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1004 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1005 LaTeXFeatures::isAvailable("xcolor");
1007 if (!dvipost && !xcolorsoul) {
1008 Alert::warning(_("Changes not shown in LaTeX output"),
1009 _("Changes will not be highlighted in LaTeX output, "
1010 "because neither dvipost nor xcolor/soul are installed.\n"
1011 "Please install these packages or redefine "
1012 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1013 } else if (!xcolorsoul) {
1014 Alert::warning(_("Changes not shown in LaTeX output"),
1015 _("Changes will not be highlighted in LaTeX output "
1016 "when using pdflatex, because xcolor and soul are not installed.\n"
1017 "Please install both packages or redefine "
1018 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1023 case LFUN_CHANGE_NEXT:
1024 findNextChange(this);
1027 case LFUN_CHANGES_MERGE:
1028 if (findNextChange(this))
1029 showDialog("changes");
1032 case LFUN_ALL_CHANGES_ACCEPT:
1033 // select complete document
1034 cursor_.reset(buffer_.inset());
1035 cursor_.selHandle(true);
1036 buffer_.text().cursorBottom(cursor_);
1037 // accept everything in a single step to support atomic undo
1038 buffer_.text().acceptOrRejectChanges(cursor_, Text::ACCEPT);
1041 case LFUN_ALL_CHANGES_REJECT:
1042 // select complete document
1043 cursor_.reset(buffer_.inset());
1044 cursor_.selHandle(true);
1045 buffer_.text().cursorBottom(cursor_);
1046 // reject everything in a single step to support atomic undo
1047 // Note: reject does not work recursively; the user may have to repeat the operation
1048 buffer_.text().acceptOrRejectChanges(cursor_, Text::REJECT);
1051 case LFUN_WORD_FIND:
1055 case LFUN_WORD_REPLACE: {
1056 bool has_deleted = false;
1057 if (cur.selection()) {
1058 DocIterator beg = cur.selectionBegin();
1059 DocIterator end = cur.selectionEnd();
1060 if (beg.pit() == end.pit()) {
1061 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1062 if (cur.paragraph().isDeleted(p))
1067 replace(this, cmd, has_deleted);
1072 cur.clearSelection();
1074 cur.message(from_utf8(N_("Mark off")));
1078 cur.clearSelection();
1081 cur.message(from_utf8(N_("Mark on")));
1084 case LFUN_MARK_TOGGLE:
1085 cur.clearSelection();
1088 cur.message(from_utf8(N_("Mark removed")));
1091 cur.message(from_utf8(N_("Mark set")));
1096 case LFUN_SCREEN_RECENTER:
1100 case LFUN_BIBTEX_DATABASE_ADD: {
1101 Cursor tmpcur = cursor_;
1102 findInset(tmpcur, Inset::BIBTEX_CODE, false);
1103 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1104 Inset::BIBTEX_CODE);
1106 if (inset->addDatabase(to_utf8(cmd.argument())))
1107 buffer_.updateBibfilesCache();
1112 case LFUN_BIBTEX_DATABASE_DEL: {
1113 Cursor tmpcur = cursor_;
1114 findInset(tmpcur, Inset::BIBTEX_CODE, false);
1115 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1116 Inset::BIBTEX_CODE);
1118 if (inset->delDatabase(to_utf8(cmd.argument())))
1119 buffer_.updateBibfilesCache();
1124 case LFUN_WORDS_COUNT: {
1125 DocIterator from, to;
1126 if (cur.selection()) {
1127 from = cur.selectionBegin();
1128 to = cur.selectionEnd();
1130 from = doc_iterator_begin(buffer_.inset());
1131 to = doc_iterator_end(buffer_.inset());
1133 int const count = countWords(from, to);
1136 if (cur.selection())
1137 message = bformat(_("%1$d words in selection."),
1140 message = bformat(_("%1$d words in document."),
1144 if (cur.selection())
1145 message = _("One word in selection.");
1147 message = _("One word in document.");
1150 Alert::information(_("Count words"), message);
1154 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1155 // turn compression on/off
1156 buffer_.params().compressed = !buffer_.params().compressed;
1159 case LFUN_NEXT_INSET_TOGGLE: {
1160 // this is the real function we want to invoke
1161 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1162 // if there is an inset at cursor, see whether it
1164 Inset * inset = cur.nextInset();
1166 if (inset->isActive()) {
1167 Cursor tmpcur = cur;
1168 tmpcur.pushLeft(*inset);
1169 inset->dispatch(tmpcur, tmpcmd);
1170 if (tmpcur.result().dispatched()) {
1173 } else if (inset->editable() == Inset::IS_EDITABLE) {
1174 inset->edit(cur, true);
1177 // if it did not work, try the underlying inset.
1178 if (!cur.result().dispatched())
1179 cur.dispatch(tmpcmd);
1181 if (cur.result().dispatched())
1182 cur.clearSelection();
1187 case LFUN_SCREEN_UP:
1188 case LFUN_SCREEN_DOWN: {
1189 Point p = getPos(cur, cur.boundary());
1190 if (p.y_ < 0 || p.y_ > height_) {
1191 // The cursor is off-screen so recenter before proceeding.
1193 updateMetrics(false);
1194 //FIXME: updateMetrics() does not update paragraph position
1195 // This is done at draw() time. So we need a redraw!
1197 p = getPos(cur, cur.boundary());
1199 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1200 cur.reset(buffer_.inset());
1201 text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1202 //FIXME: what to do with cur.x_target()?
1204 // The metrics are already up to date. see scroll()
1205 updateFlags = Update::None;
1209 case LFUN_SCREEN_UP_SELECT:
1210 case LFUN_SCREEN_DOWN_SELECT: {
1211 cur.selHandle(true);
1212 size_t initial_depth = cur.depth();
1213 Point const p = getPos(cur, cur.boundary());
1214 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1215 // FIXME: We need to verify if the cursor stayed within an inset...
1216 //cur.reset(buffer_.inset());
1217 text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1219 while (cur.depth() > initial_depth) {
1222 // FIXME: we need to do a redraw again because of the selection
1224 updateFlags = Update::Force | Update::FitCursor;
1229 updateFlags = Update::None;
1236 docstring const BufferView::requestSelection()
1238 Cursor & cur = cursor_;
1240 if (!cur.selection()) {
1241 xsel_cache_.set = false;
1245 if (!xsel_cache_.set ||
1246 cur.top() != xsel_cache_.cursor ||
1247 cur.anchor_.top() != xsel_cache_.anchor)
1249 xsel_cache_.cursor = cur.top();
1250 xsel_cache_.anchor = cur.anchor_.top();
1251 xsel_cache_.set = cur.selection();
1252 return cur.selectionAsString(false);
1258 void BufferView::clearSelection()
1260 cursor_.clearSelection();
1261 // Clear the selection buffer. Otherwise a subsequent
1262 // middle-mouse-button paste would use the selection buffer,
1263 // not the more current external selection.
1264 cap::clearSelection();
1265 xsel_cache_.set = false;
1266 // The buffer did not really change, but this causes the
1267 // redraw we need because we cleared the selection above.
1272 void BufferView::resize(int width, int height)
1274 // Update from work area
1278 updateMetrics(false);
1282 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1284 TextMetrics & tm = text_metrics_[&text];
1285 Inset * inset = tm.checkInsetHit(x, y);
1289 if (!inset->descendable())
1290 // No need to go further down if the inset is not
1294 size_t cell_number = inset->nargs();
1295 // Check all the inner cell.
1296 for (size_t i = 0; i != cell_number; ++i) {
1297 Text const * inner_text = inset->getText(i);
1300 Inset const * inset_deeper =
1301 getCoveringInset(*inner_text, x, y);
1303 return inset_deeper;
1311 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1313 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1315 // This is only called for mouse related events including
1316 // LFUN_FILE_OPEN generated by drag-and-drop.
1317 FuncRequest cmd = cmd0;
1320 cur.push(buffer_.inset());
1321 cur.selection() = cursor_.selection();
1323 // Either the inset under the cursor or the
1324 // surrounding Text will handle this event.
1326 // make sure we stay within the screen...
1327 cmd.y = min(max(cmd.y, -1), height_);
1329 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1331 // Get inset under mouse, if there is one.
1332 Inset const * covering_inset =
1333 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1334 if (covering_inset == last_inset_)
1335 // Same inset, no need to do anything...
1338 bool need_redraw = false;
1339 // const_cast because of setMouseHover().
1340 Inset * inset = const_cast<Inset *>(covering_inset);
1342 // Remove the hint on the last hovered inset (if any).
1343 need_redraw |= last_inset_->setMouseHover(false);
1345 // Highlighted the newly hovered inset (if any).
1346 need_redraw |= inset->setMouseHover(true);
1347 last_inset_ = inset;
1351 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1352 // not expose the button for redraw. We adjust here the metrics dimension
1353 // to enable a full redraw in any case as this is not costly.
1354 TextMetrics & tm = text_metrics_[&buffer_.text()];
1355 std::pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
1356 std::pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1357 int y1 = firstpm.second->position() - firstpm.second->ascent();
1358 int y2 = lastpm.second->position() + lastpm.second->descent();
1359 metrics_info_ = ViewMetricsInfo(firstpm.first, lastpm.first, y1, y2,
1360 FullScreenUpdate, buffer_.text().paragraphs().size());
1361 // Reinitialize anchor to first pit.
1362 anchor_ref_ = firstpm.first;
1364 LYXERR(Debug::PAINTING)
1365 << "Mouse hover detected at: (" << cmd.x << ", " << cmd.y << ")"
1366 << "\nTriggering redraw: y1: " << y1 << " y2: " << y2
1367 << " pit1: " << firstpm.first << " pit2: " << lastpm.first << endl;
1369 // This event (moving without mouse click) is not passed further.
1370 // This should be changed if it is further utilized.
1374 // Build temporary cursor.
1375 Inset * inset = text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1377 // Put anchor at the same position.
1380 // Try to dispatch to an non-editable inset near this position
1381 // via the temp cursor. If the inset wishes to change the real
1382 // cursor it has to do so explicitly by using
1383 // cur.bv().cursor() = cur; (or similar)
1385 inset->dispatch(cur, cmd);
1388 // Now dispatch to the temporary cursor. If the real cursor should
1389 // be modified, the inset's dispatch has to do so explicitly.
1390 if (!cur.result().dispatched())
1393 //Do we have a selection?
1394 theSelection().haveSelection(cursor().selection());
1396 // Redraw if requested and necessary.
1397 if (cur.result().dispatched() && cur.result().update())
1398 return update(cur.result().update());
1404 void BufferView::scroll(int y)
1413 void BufferView::scrollDown(int offset)
1415 Text * text = &buffer_.text();
1416 TextMetrics & tm = text_metrics_[text];
1417 int ymax = height_ + offset;
1419 std::pair<pit_type, ParagraphMetrics const *> last = tm.last();
1420 int bottom_pos = last.second->position() + last.second->descent();
1421 if (last.first + 1 == int(text->paragraphs().size())) {
1422 if (bottom_pos <= height_)
1424 offset = min(offset, bottom_pos - height_);
1427 if (bottom_pos > ymax)
1429 tm.newParMetricsDown();
1431 offset_ref_ += offset;
1432 updateMetrics(false);
1437 void BufferView::scrollUp(int offset)
1439 Text * text = &buffer_.text();
1440 TextMetrics & tm = text_metrics_[text];
1441 int ymin = - offset;
1443 std::pair<pit_type, ParagraphMetrics const *> first = tm.first();
1444 int top_pos = first.second->position() - first.second->ascent();
1445 if (first.first == 0) {
1448 offset = min(offset, - top_pos);
1453 tm.newParMetricsUp();
1455 offset_ref_ -= offset;
1456 updateMetrics(false);
1461 void BufferView::setCursorFromRow(int row)
1466 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1468 cursor_.reset(buffer_.inset());
1470 buffer_.text().setCursor(cursor_, 0, 0);
1472 buffer_.text().setCursor(cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1476 void BufferView::gotoLabel(docstring const & label)
1478 for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1479 vector<docstring> labels;
1480 it->getLabelList(buffer_, labels);
1481 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1490 TextMetrics const & BufferView::textMetrics(Text const * t) const
1492 return const_cast<BufferView *>(this)->textMetrics(t);
1496 TextMetrics & BufferView::textMetrics(Text const * t)
1498 TextMetricsCache::iterator tmc_it = text_metrics_.find(t);
1499 if (tmc_it == text_metrics_.end()) {
1500 tmc_it = text_metrics_.insert(
1501 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1503 return tmc_it->second;
1507 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1510 return textMetrics(t).parMetrics(pit);
1514 int BufferView::workHeight() const
1520 void BufferView::setCursor(DocIterator const & dit)
1522 size_t const n = dit.depth();
1523 for (size_t i = 0; i < n; ++i)
1524 dit[i].inset().edit(cursor_, true);
1526 cursor_.setCursor(dit);
1527 cursor_.selection() = false;
1531 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1533 // Would be wrong to delete anything if we have a selection.
1534 if (cur.selection())
1537 bool need_anchor_change = false;
1538 bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1539 need_anchor_change);
1541 if (need_anchor_change)
1547 updateLabels(buffer_);
1549 updateMetrics(false);
1555 bool BufferView::mouseSetCursor(Cursor & cur)
1557 BOOST_ASSERT(&cur.bv() == this);
1559 // this event will clear selection so we save selection for
1560 // persistent selection
1561 cap::saveSelection(cursor());
1563 // Has the cursor just left the inset?
1564 bool badcursor = false;
1565 bool leftinset = (&cursor_.inset() != &cur.inset());
1567 badcursor = notifyCursorLeaves(cursor_, cur);
1569 // do the dEPM magic if needed
1570 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1571 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1572 // the leftinset bool would not be necessary (badcursor instead).
1573 bool update = leftinset;
1574 if (!badcursor && cursor_.inTexted())
1575 update |= checkDepm(cur, cursor_);
1577 // if the cursor was in an empty script inset and the new
1578 // position is in the nucleus of the inset, notifyCursorLeaves
1579 // will kill the script inset itself. So we check all the
1580 // elements of the cursor to make sure that they are correct.
1581 // For an example, see bug 2933:
1582 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1583 // The code below could maybe be moved to a DocIterator method.
1584 //lyxerr << "cur before " << cur <<std::endl;
1585 DocIterator dit(cur.inset());
1586 dit.push_back(cur.bottom());
1588 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1589 dit.push_back(cur[i]);
1592 //lyxerr << "5 cur after" << dit <<std::endl;
1594 cursor_.setCursor(dit);
1595 cursor_.boundary(cur.boundary());
1596 cursor_.clearSelection();
1602 void BufferView::putSelectionAt(DocIterator const & cur,
1603 int length, bool backwards)
1605 cursor_.clearSelection();
1611 cursor_.pos() += length;
1612 cursor_.setSelection(cursor_, -length);
1614 cursor_.setSelection(cursor_, length);
1619 Cursor & BufferView::cursor()
1625 Cursor const & BufferView::cursor() const
1631 pit_type BufferView::anchor_ref() const
1637 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1639 return metrics_info_;
1643 bool BufferView::singleParUpdate()
1645 Text & buftext = buffer_.text();
1646 pit_type const bottom_pit = cursor_.bottom().pit();
1647 TextMetrics & tm = textMetrics(&buftext);
1648 int old_height = tm.parMetrics(bottom_pit).height();
1650 // In Single Paragraph mode, rebreak only
1651 // the (main text, not inset!) paragraph containing the cursor.
1652 // (if this paragraph contains insets etc., rebreaking will
1653 // recursively descend)
1654 tm.redoParagraph(bottom_pit);
1655 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
1656 if (pm.height() != old_height)
1657 // Paragraph height has changed so we cannot proceed to
1658 // the singlePar optimisation.
1661 int y1 = pm.position() - pm.ascent();
1662 int y2 = pm.position() + pm.descent();
1663 metrics_info_ = ViewMetricsInfo(bottom_pit, bottom_pit, y1, y2,
1664 SingleParUpdate, buftext.paragraphs().size());
1665 LYXERR(Debug::PAINTING)
1666 << BOOST_CURRENT_FUNCTION
1669 << " pit: " << bottom_pit
1676 void BufferView::updateMetrics(bool singlepar)
1678 if (singlepar && singleParUpdate())
1679 // No need to update the full screen metrics.
1682 Text & buftext = buffer_.text();
1683 pit_type const npit = int(buftext.paragraphs().size());
1685 if (anchor_ref_ > int(npit - 1)) {
1686 anchor_ref_ = int(npit - 1);
1690 // Clear out the position cache in case of full screen redraw,
1691 coord_cache_.clear();
1693 // Clear out paragraph metrics to avoid having invalid metrics
1694 // in the cache from paragraphs not relayouted below
1695 // The complete text metrics will be redone.
1696 text_metrics_.clear();
1698 TextMetrics & tm = textMetrics(&buftext);
1700 pit_type const pit = anchor_ref_;
1704 // Rebreak anchor paragraph.
1705 tm.redoParagraph(pit);
1707 // Take care of anchor offset if case a recentering is needed.
1710 int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1712 // Redo paragraphs above anchor if necessary.
1714 while (y1 > 0 && pit1 > 0) {
1715 y1 -= tm.parMetrics(pit1).ascent();
1717 tm.redoParagraph(pit1);
1718 y1 -= tm.parMetrics(pit1).descent();
1721 // Take care of ascent of first line
1722 y1 -= tm.parMetrics(pit1).ascent();
1724 // Normalize anchor for next time
1728 // Grey at the beginning is ugly
1729 if (pit1 == 0 && y1 > 0) {
1735 // Redo paragraphs below the anchor if necessary.
1737 while (y2 < height_ && pit2 < int(npit) - 1) {
1738 y2 += tm.parMetrics(pit2).descent();
1740 tm.redoParagraph(pit2);
1741 y2 += tm.parMetrics(pit2).ascent();
1744 // Take care of descent of last line
1745 y2 += tm.parMetrics(pit2).descent();
1747 LYXERR(Debug::PAINTING)
1748 << BOOST_CURRENT_FUNCTION
1751 << " pit1: " << pit1
1752 << " pit2: " << pit2
1753 << " npit: " << npit
1757 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1758 FullScreenUpdate, npit);
1760 if (lyxerr.debugging(Debug::WORKAREA)) {
1761 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1762 coord_cache_.dump();
1767 void BufferView::menuInsertLyXFile(string const & filenm)
1769 BOOST_ASSERT(cursor_.inTexted());
1770 string filename = filenm;
1772 if (filename.empty()) {
1773 // Launch a file browser
1775 string initpath = lyxrc.document_path;
1776 string const trypath = buffer_.filePath();
1777 // If directory is writeable, use this as default.
1778 if (isDirWriteable(FileName(trypath)))
1782 FileDialog fileDlg(_("Select LyX document to insert"),
1784 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1785 make_pair(_("Examples|#E#e"),
1786 from_utf8(addPath(package().system_support().absFilename(),
1789 FileDialog::Result result =
1790 fileDlg.open(from_utf8(initpath),
1791 FileFilterList(_("LyX Documents (*.lyx)")),
1794 if (result.first == FileDialog::Later)
1798 filename = to_utf8(result.second);
1800 // check selected filename
1801 if (filename.empty()) {
1802 // emit message signal.
1803 message(_("Canceled."));
1808 // Get absolute path of file and add ".lyx"
1809 // to the filename if necessary
1810 filename = fileSearch(string(), filename, "lyx").absFilename();
1812 docstring const disp_fn = makeDisplayPath(filename);
1813 // emit message signal.
1814 message(bformat(_("Inserting document %1$s..."), disp_fn));
1817 Buffer buf("", false);
1818 if (lyx::loadLyXFile(&buf, FileName(filename))) {
1819 ErrorList & el = buffer_.errorList("Parse");
1820 // Copy the inserted document error list into the current buffer one.
1821 el = buf.errorList("Parse");
1822 recordUndo(cursor_);
1823 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1824 buf.params().getTextClassPtr(), el);
1825 res = _("Document %1$s inserted.");
1827 res = _("Could not insert document %1$s");
1829 // emit message signal.
1830 message(bformat(res, disp_fn));
1831 buffer_.errors("Parse");
1832 updateMetrics(false);
1836 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1842 // Addup contribution of nested insets, from inside to outside,
1843 // keeping the outer paragraph for a special handling below
1844 for (size_t i = dit.depth() - 1; i >= 1; --i) {
1845 CursorSlice const & sl = dit[i];
1849 // get relative position inside sl.inset()
1850 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
1852 // Make relative position inside of the edited inset relative to sl.inset()
1856 // In case of an RTL inset, the edited inset will be positioned to the left
1859 bool boundary_i = boundary && i + 1 == dit.depth();
1860 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
1865 // remember width for the case that sl.inset() is positioned in an RTL inset
1866 if (i && dit[i - 1].text()) {
1867 // If this Inset is inside a Text Inset, retrieve the Dimension
1868 // from the containing text instead of using Inset::dimension() which
1869 // might not be implemented.
1870 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
1871 // elimination of Inset::dim_ cache. This coordOffset() method needs
1872 // to be rewritten in light of the new design.
1873 Dimension const & dim = parMetrics(dit[i - 1].text(),
1874 dit[i - 1].pit()).insetDimension(&sl.inset());
1877 Dimension const dim = sl.inset().dimension(*this);
1881 //lyxerr << "Cursor::getPos, i: "
1882 // << i << " x: " << xx << " y: " << y << endl;
1885 // Add contribution of initial rows of outermost paragraph
1886 CursorSlice const & sl = dit[0];
1887 TextMetrics const & tm = textMetrics(sl.text());
1888 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
1889 BOOST_ASSERT(!pm.rows().empty());
1890 y -= pm.rows()[0].ascent();
1892 // FIXME: document this mess
1894 if (sl.pos() > 0 && dit.depth() == 1) {
1896 if (pos && boundary)
1898 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << std::endl;
1899 rend = pm.pos2row(pos);
1901 rend = pm.pos2row(sl.pos());
1903 size_t rend = pm.pos2row(sl.pos());
1905 for (size_t rit = 0; rit != rend; ++rit)
1906 y += pm.rows()[rit].height();
1907 y += pm.rows()[rend].ascent();
1909 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
1911 // Make relative position from the nested inset now bufferview absolute.
1912 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
1915 // In the RTL case place the nested inset at the left of the cursor in
1916 // the outer paragraph
1917 bool boundary_1 = boundary && 1 == dit.depth();
1918 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
1926 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
1928 CursorSlice const & bot = dit.bottom();
1929 TextMetrics const & tm = textMetrics(bot.text());
1930 if (!tm.has(bot.pit()))
1931 return Point(-1, -1);
1933 Point p = coordOffset(dit, boundary); // offset from outer paragraph
1934 p.y_ += tm.parMetrics(bot.pit()).position();
1939 void BufferView::draw(frontend::Painter & pain)
1941 PainterInfo pi(this, pain);
1942 // Should the whole screen, including insets, be refreshed?
1943 // FIXME: We should also distinguish DecorationUpdate to avoid text
1944 // drawing if possible. This is not possible to do easily right now
1945 // because of the single backing pixmap.
1946 pi.full_repaint = metrics_info_.update_strategy != SingleParUpdate;
1948 if (pi.full_repaint)
1949 // Clear background (if not delegated to rows)
1950 pain.fillRectangle(0, metrics_info_.y1, width_,
1951 metrics_info_.y2 - metrics_info_.y1,
1952 buffer_.inset().backgroundColor());
1954 LYXERR(Debug::PAINTING) << "\t\t*** START DRAWING ***" << endl;
1955 Text & text = buffer_.text();
1956 TextMetrics const & tm = text_metrics_[&text];
1957 int y = metrics_info_.y1 + tm.parMetrics(metrics_info_.p1).ascent();
1958 if (!pi.full_repaint)
1959 tm.drawParagraph(pi, metrics_info_.p1, 0, y);
1962 LYXERR(Debug::PAINTING) << "\n\t\t*** END DRAWING ***" << endl;
1964 // and grey out above (should not happen later)
1965 // lyxerr << "par ascent: " << text.getPar(metrics_info_.p1).ascent() << endl;
1966 if (metrics_info_.y1 > 0
1967 && metrics_info_.update_strategy == FullScreenUpdate)
1968 pain.fillRectangle(0, 0, width_, metrics_info_.y1, Color::bottomarea);
1970 // and possibly grey out below
1971 // lyxerr << "par descent: " << text.getPar(metrics_info_.p1).ascent() << endl;
1972 if (metrics_info_.y2 < height_
1973 && metrics_info_.update_strategy == FullScreenUpdate)
1974 pain.fillRectangle(0, metrics_info_.y2, width_,
1975 height_ - metrics_info_.y2, Color::bottomarea);
1979 void BufferView::message(docstring const & msg)
1986 void BufferView::showDialog(std::string const & name)
1989 gui_->showDialog(name);
1993 void BufferView::showDialogWithData(std::string const & name,
1994 std::string const & data)
1997 gui_->showDialogWithData(name, data);
2001 void BufferView::showInsetDialog(std::string const & name,
2002 std::string const & data, Inset * inset)
2005 gui_->showInsetDialog(name, data, inset);
2009 void BufferView::updateDialog(std::string const & name, std::string const & data)
2012 gui_->updateDialog(name, data);
2016 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2022 static docstring contentsOfPlaintextFile(BufferView * bv, string const & f,
2027 if (fname.empty()) {
2028 FileDialog fileDlg(_("Select file to insert"),
2030 ? LFUN_FILE_INSERT_PLAINTEXT_PARA
2031 : LFUN_FILE_INSERT_PLAINTEXT) );
2033 FileDialog::Result result =
2034 fileDlg.open(from_utf8(bv->buffer().filePath()),
2035 FileFilterList(), docstring());
2037 if (result.first == FileDialog::Later)
2040 fname = makeAbsPath(to_utf8(result.second));
2046 if (!fs::is_readable(fname.toFilesystemEncoding())) {
2047 docstring const error = from_ascii(strerror(errno));
2048 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2049 docstring const text =
2050 bformat(_("Could not read the specified document\n"
2051 "%1$s\ndue to the error: %2$s"), file, error);
2052 Alert::error(_("Could not read file"), text);
2056 ifstream ifs(fname.toFilesystemEncoding().c_str());
2058 docstring const error = from_ascii(strerror(errno));
2059 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2060 docstring const text =
2061 bformat(_("Could not open the specified document\n"
2062 "%1$s\ndue to the error: %2$s"), file, error);
2063 Alert::error(_("Could not open file"), text);
2067 ifs.unsetf(ios::skipws);
2068 istream_iterator<char> ii(ifs);
2069 istream_iterator<char> end;
2070 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
2071 // We use this until the compilers get better...
2072 std::vector<char> tmp;
2073 copy(ii, end, back_inserter(tmp));
2074 string const tmpstr(tmp.begin(), tmp.end());
2076 // This is what we want to use and what we will use once the
2077 // compilers get good enough.
2078 //string tmpstr(ii, end); // yet a reason for using std::string
2079 // alternate approach to get the file into a string:
2081 copy(ii, end, back_inserter(tmpstr));
2084 // FIXME UNICODE: We don't know the encoding of the file
2085 docstring file_content = from_utf8(tmpstr);
2086 if (file_content.empty()) {
2087 Alert::error(_("Reading not UTF-8 encoded file"),
2088 _("The file is not UTF-8 encoded.\n"
2089 "It will be read as local 8Bit-encoded.\n"
2090 "If this does not give the correct result\n"
2091 "then please change the encoding of the file\n"
2092 "to UTF-8 with a program other than LyX.\n"));
2093 file_content = from_local8bit(tmpstr);
2096 return normalize_c(file_content);
2099 // Insert plain text file (if filename is empty, prompt for one)
2100 void BufferView::insertPlaintextFile(string const & f, bool asParagraph)
2102 docstring const tmpstr =
2103 contentsOfPlaintextFile(this, f, asParagraph);
2108 Cursor & cur = cursor();
2109 cap::replaceSelection(cur);
2112 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2114 cur.innerText()->insertStringAsLines(cur, tmpstr);