2 * \file buffer_funcs.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Alfredo Braunstein
9 * Full author contact details are available in file CREDITS.
15 #include "buffer_funcs.h"
17 #include "BufferList.h"
18 #include "BufferParams.h"
19 #include "DocIterator.h"
21 #include "ErrorList.h"
23 #include "FloatList.h"
27 #include "TextClass.h"
28 #include "Paragraph.h"
29 #include "paragraph_funcs.h"
30 #include "ParagraphList.h"
31 #include "ParagraphParameters.h"
32 #include "ParIterator.h"
35 #include "TocBackend.h"
36 #include "VCBackend.h"
38 #include "frontends/alert.h"
40 #include "insets/InsetBibitem.h"
41 #include "insets/InsetCaption.h"
42 #include "insets/InsetInclude.h"
43 #include "insets/InsetTabular.h"
45 #include "support/filetools.h"
46 #include "support/fs_extras.h"
47 #include "support/lyxlib.h"
49 #include <boost/bind.hpp>
50 #include <boost/filesystem/operations.hpp>
57 using support::bformat;
58 using support::FileName;
59 using support::libFileSearch;
60 using support::makeAbsPath;
61 using support::makeDisplayPath;
62 using support::onlyFilename;
63 using support::onlyPath;
64 using support::unlink;
69 namespace Alert = frontend::Alert;
70 namespace fs = boost::filesystem;
74 bool readFile(Buffer * const b, FileName const & s)
78 // File information about normal file
79 if (!fs::exists(s.toFilesystemEncoding())) {
80 docstring const file = makeDisplayPath(s.absFilename(), 50);
81 docstring text = bformat(_("The specified document\n%1$s"
82 "\ncould not be read."), file);
83 Alert::error(_("Could not read document"), text);
87 // Check if emergency save file exists and is newer.
88 FileName const e(s.absFilename() + ".emergency");
90 if (fs::exists(e.toFilesystemEncoding()) &&
91 fs::exists(s.toFilesystemEncoding()) &&
92 fs::last_write_time(e.toFilesystemEncoding()) > fs::last_write_time(s.toFilesystemEncoding()))
94 docstring const file = makeDisplayPath(s.absFilename(), 20);
95 docstring const text =
96 bformat(_("An emergency save of the document "
98 "Recover emergency save?"), file);
99 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
100 _("&Recover"), _("&Load Original"),
104 // the file is not saved if we load the emergency file.
106 return b->readFile(e);
114 // Now check if autosave file is newer.
115 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
117 if (fs::exists(a.toFilesystemEncoding()) &&
118 fs::exists(s.toFilesystemEncoding()) &&
119 fs::last_write_time(a.toFilesystemEncoding()) > fs::last_write_time(s.toFilesystemEncoding()))
121 docstring const file = makeDisplayPath(s.absFilename(), 20);
122 docstring const text =
123 bformat(_("The backup of the document "
124 "%1$s is newer.\n\nLoad the "
125 "backup instead?"), file);
126 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
127 _("&Load backup"), _("Load &original"),
131 // the file is not saved if we load the autosave file.
133 return b->readFile(a);
135 // Here we delete the autosave
142 return b->readFile(s);
150 bool loadLyXFile(Buffer * b, FileName const & s)
154 if (fs::is_readable(s.toFilesystemEncoding())) {
155 if (readFile(b, s)) {
156 b->lyxvc().file_found_hook(s);
157 if (!fs::is_writable(s.toFilesystemEncoding()))
158 b->setReadonly(true);
162 docstring const file = makeDisplayPath(s.absFilename(), 20);
163 // Here we probably should run
164 if (LyXVC::file_not_found_hook(s)) {
165 docstring const text =
166 bformat(_("Do you want to retrieve the document"
167 " %1$s from version control?"), file);
168 int const ret = Alert::prompt(_("Retrieve from version control?"),
169 text, 0, 1, _("&Retrieve"), _("&Cancel"));
172 // How can we know _how_ to do the checkout?
173 // With the current VC support it has to be,
174 // a RCS file since CVS do not have special ,v files.
176 return loadLyXFile(b, s);
183 // FIXME newFile() should probably be a member method of Application...
184 Buffer * newFile(string const & filename, string const & templatename,
188 Buffer * b = theBufferList().newBuffer(filename);
192 // use defaults.lyx as a default template if it exists.
193 if (templatename.empty())
194 tname = libFileSearch("templates", "defaults.lyx");
196 tname = makeAbsPath(templatename);
198 if (!tname.empty()) {
199 if (!b->readFile(tname)) {
200 docstring const file = makeDisplayPath(tname.absFilename(), 50);
201 docstring const text = bformat(
202 _("The specified document template\n%1$s\ncould not be read."),
204 Alert::error(_("Could not read template"), text);
205 theBufferList().release(b);
212 b->setFileName(filename);
215 b->setReadonly(false);
216 b->fully_loaded(true);
222 void bufferErrors(Buffer const & buf, TeXErrors const & terr,
223 ErrorList & errorList)
225 TeXErrors::Errors::const_iterator cit = terr.begin();
226 TeXErrors::Errors::const_iterator end = terr.end();
228 for (; cit != end; ++cit) {
231 int errorrow = cit->error_in_line;
232 bool found = buf.texrow().getIdFromRow(errorrow, id_start,
238 found = buf.texrow().getIdFromRow(errorrow, id_end,
240 } while (found && id_start == id_end && pos_start == pos_end);
242 errorList.push_back(ErrorItem(cit->error_desc,
243 cit->error_text, id_start, pos_start, pos_end));
248 string const bufferFormat(Buffer const & buffer)
250 if (buffer.isDocBook())
252 else if (buffer.isLiterate())
259 int countWords(DocIterator const & from, DocIterator const & to)
263 for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
264 // Copied and adapted from isLetter() in ControlSpellChecker
266 && dit.pos() != dit.lastpos()
267 && dit.paragraph().isLetter(dit.pos())
268 && !dit.paragraph().isDeleted(dit.pos())) {
283 depth_type getDepth(DocIterator const & it)
285 depth_type depth = 0;
286 for (size_t i = 0 ; i < it.depth() ; ++i)
287 if (!it[i].inset().inMathed())
288 depth += it[i].paragraph().getDepth() + 1;
289 // remove 1 since the outer inset does not count
293 depth_type getItemDepth(ParIterator const & it)
295 Paragraph const & par = *it;
296 LYX_LABEL_TYPES const labeltype = par.layout()->labeltype;
298 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
301 // this will hold the lowest depth encountered up to now.
302 depth_type min_depth = getDepth(it);
303 ParIterator prev_it = it;
306 --prev_it.top().pit();
308 // start of nested inset: go to outer par
310 if (prev_it.empty()) {
311 // start of document: nothing to do
316 // We search for the first paragraph with same label
317 // that is not more deeply nested.
318 Paragraph & prev_par = *prev_it;
319 depth_type const prev_depth = getDepth(prev_it);
320 if (labeltype == prev_par.layout()->labeltype) {
321 if (prev_depth < min_depth) {
322 return prev_par.itemdepth + 1;
324 else if (prev_depth == min_depth) {
325 return prev_par.itemdepth;
328 min_depth = std::min(min_depth, prev_depth);
329 // small optimization: if we are at depth 0, we won't
330 // find anything else
331 if (prev_depth == 0) {
338 bool needEnumCounterReset(ParIterator const & it)
340 Paragraph const & par = *it;
341 BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
342 depth_type const cur_depth = par.getDepth();
343 ParIterator prev_it = it;
344 while (prev_it.pit()) {
345 --prev_it.top().pit();
346 Paragraph const & prev_par = *prev_it;
347 if (prev_par.getDepth() <= cur_depth)
348 return prev_par.layout()->labeltype != LABEL_ENUMERATE;
350 // start of nested inset: reset
355 void setCaptionLabels(Inset & inset, string const & type,
356 docstring const label, Counters & counters)
358 Text * text = inset.getText(0);
362 ParagraphList & pars = text->paragraphs();
366 docstring const counter = from_ascii(type);
368 ParagraphList::iterator p = pars.begin();
369 for (; p != pars.end(); ++p) {
370 InsetList::iterator it2 = p->insetlist.begin();
371 InsetList::iterator end2 = p->insetlist.end();
372 // Any caption within this float should have the same
373 // label prefix but different numbers.
374 for (; it2 != end2; ++it2) {
375 Inset & icap = *it2->inset;
376 // Look deeper just in case.
377 setCaptionLabels(icap, type, label, counters);
378 if (icap.lyxCode() == Inset::CAPTION_CODE) {
379 // We found a caption!
380 counters.step(counter);
381 int number = counters.value(counter);
382 InsetCaption & ic = static_cast<InsetCaption &>(icap);
385 ic.setCustomLabel(label);
392 void setCaptions(Paragraph & par, TextClass const & textclass)
394 if (par.insetlist.empty())
397 Counters & counters = textclass.counters();
399 InsetList::iterator it = par.insetlist.begin();
400 InsetList::iterator end = par.insetlist.end();
401 for (; it != end; ++it) {
402 Inset & inset = *it->inset;
403 if (inset.lyxCode() == Inset::FLOAT_CODE
404 || inset.lyxCode() == Inset::WRAP_CODE) {
405 docstring const name = inset.name();
409 Floating const & fl = textclass.floats().getType(to_ascii(name));
411 string const & type = fl.type();
412 docstring const label = from_utf8(fl.name());
413 setCaptionLabels(inset, type, label, counters);
415 else if (inset.lyxCode() == Inset::TABULAR_CODE
416 && static_cast<InsetTabular &>(inset).tabular.isLongTabular()) {
417 // FIXME: are "table" and "Table" the correct type and label?
418 setCaptionLabels(inset, "table", from_ascii("Table"), counters);
423 // set the label of a paragraph. This includes the counters.
424 void setLabel(Buffer const & buf, ParIterator & it, TextClass const & textclass)
426 Paragraph & par = *it;
427 Layout_ptr const & layout = par.layout();
428 Counters & counters = textclass.counters();
431 par.params().appendix(par.params().startOfAppendix());
433 par.params().appendix(it.plist()[it.pit() - 1].params().appendix());
434 if (!par.params().appendix() &&
435 par.params().startOfAppendix()) {
436 par.params().appendix(true);
437 textclass.counters().reset();
441 // Compute the item depth of the paragraph
442 par.itemdepth = getItemDepth(it);
444 if (layout->margintype == MARGIN_MANUAL) {
445 if (par.params().labelWidthString().empty())
446 par.params().labelWidthString(par.translateIfPossible(layout->labelstring(), buf.params()));
448 par.params().labelWidthString(docstring());
451 // Optimisation: setLabel() can be called for each for each
452 // paragraph of the document. So we make the string static to
453 // avoid the repeated instanciation.
454 static docstring itemlabel;
456 // is it a layout that has an automatic label?
457 if (layout->labeltype == LABEL_COUNTER) {
458 if (layout->toclevel <= buf.params().secnumdepth
459 && (layout->latextype != LATEX_ENVIRONMENT
460 || isFirstInSequence(it.pit(), it.plist()))) {
461 counters.step(layout->counter);
462 par.params().labelString(
463 par.expandLabel(layout, buf.params()));
465 par.params().labelString(docstring());
467 } else if (layout->labeltype == LABEL_ITEMIZE) {
468 // At some point of time we should do something more
469 // clever here, like:
470 // par.params().labelString(
471 // buf.params().user_defined_bullet(par.itemdepth).getText());
472 // for now, use a simple hardcoded label
473 switch (par.itemdepth) {
475 itemlabel = char_type(0x2022);
478 itemlabel = char_type(0x2013);
481 itemlabel = char_type(0x2217);
484 itemlabel = char_type(0x2219); // or 0x00b7
487 par.params().labelString(itemlabel);
489 } else if (layout->labeltype == LABEL_ENUMERATE) {
491 // Yes I know this is a really, really! bad solution
493 docstring enumcounter = from_ascii("enum");
495 switch (par.itemdepth) {
507 // not a valid enumdepth...
511 // Maybe we have to reset the enumeration counter.
512 if (needEnumCounterReset(it))
513 counters.reset(enumcounter);
515 counters.step(enumcounter);
519 switch (par.itemdepth) {
521 format = N_("\\arabic{enumi}.");
524 format = N_("(\\alph{enumii})");
527 format = N_("\\roman{enumiii}.");
530 format = N_("\\Alph{enumiv}.");
533 // not a valid enumdepth...
537 par.params().labelString(counters.counterLabel(
538 par.translateIfPossible(from_ascii(format), buf.params())));
540 } else if (layout->labeltype == LABEL_BIBLIO) {// ale970302
541 counters.step(from_ascii("bibitem"));
542 int number = counters.value(from_ascii("bibitem"));
544 par.bibitem()->setCounter(number);
546 par.params().labelString(
547 par.translateIfPossible(layout->labelstring(), buf.params()));
548 // In biblio shouldn't be following counters but...
549 } else if (layout->labeltype == LABEL_SENSITIVE) {
550 // Search for the first float or wrap inset in the iterator
551 size_t i = it.depth();
555 Inset::Code const code = it[i].inset().lyxCode();
556 if (code == Inset::FLOAT_CODE ||
557 code == Inset::WRAP_CODE) {
562 // FIXME Can Inset::name() return an empty name for wide or
563 // float insets? If not we can put the definition of type
564 // inside the if (in) clause and use that instead of
565 // if (!type.empty()).
571 Floating const & fl = textclass.floats().getType(to_ascii(type));
573 counters.step(from_ascii(fl.type()));
575 // Doesn't work... yet.
576 par.params().labelString(par.translateIfPossible(
577 bformat(from_ascii("%1$s #:"), from_utf8(fl.name())),
580 // par->SetLayout(0);
581 par.params().labelString(par.translateIfPossible(
582 layout->labelstring(), buf.params()));
585 } else if (layout->labeltype == LABEL_NO_LABEL)
586 par.params().labelString(docstring());
588 par.params().labelString(
589 par.translateIfPossible(layout->labelstring(), buf.params()));
595 bool updateCurrentLabel(Buffer const & buf,
598 if (it == par_iterator_end(buf.inset()))
601 // if (it.lastpit == 0 && Text::isMainText(buf))
604 switch (it->layout()->labeltype) {
609 case LABEL_TOP_ENVIRONMENT:
610 case LABEL_CENTERED_TOP_ENVIRONMENT:
613 setLabel(buf, it, buf.params().getTextClass());
616 case LABEL_SENSITIVE:
618 // do more things with enumerate later
619 case LABEL_ENUMERATE:
623 // This is dead code which get rid of a warning:
628 void updateLabels(Buffer const & buf,
629 ParIterator & from, ParIterator & to, bool childonly)
631 for (ParIterator it = from; it != to; ++it) {
632 if (it.pit() > it.lastpit())
634 if (!updateCurrentLabel (buf, it)) {
635 updateLabels(buf, childonly);
642 void updateLabels(Buffer const & buf, ParIterator & iter, bool childonly)
644 if (updateCurrentLabel(buf, iter))
647 updateLabels(buf, childonly);
651 void updateLabels(Buffer const & buf, bool childonly)
653 // Use the master text class also for child documents
654 TextClass const & textclass = buf.params().getTextClass();
657 // If this is a child document start with the master
658 Buffer const * const master = buf.getMasterBuffer();
659 if (master != &buf) {
660 updateLabels(*master);
664 // start over the counters
665 textclass.counters().reset();
668 ParIterator const end = par_iterator_end(buf.inset());
670 for (ParIterator it = par_iterator_begin(buf.inset()); it != end; ++it) {
671 // reduce depth if necessary
673 Paragraph const & prevpar = it.plist()[it.pit() - 1];
674 it->params().depth(min(it->params().depth(),
675 prevpar.getMaxDepthAfter()));
677 it->params().depth(0);
679 // set the counter for this paragraph
680 setLabel(buf, it, textclass);
682 // It is better to set the captions after setLabel because
683 // the caption number might need the section number in the
685 setCaptions(*it, textclass);
688 InsetList::const_iterator iit = it->insetlist.begin();
689 InsetList::const_iterator end = it->insetlist.end();
690 for (; iit != end; ++iit) {
691 if (iit->inset->lyxCode() == Inset::INCLUDE_CODE)
692 static_cast<InsetInclude const *>(iit->inset)
697 Buffer & cbuf = const_cast<Buffer &>(buf);
698 cbuf.tocBackend().update();
699 cbuf.structureChanged();
703 void checkBufferStructure(Buffer & buffer, ParIterator const & par_it)
705 if (par_it->layout()->labeltype == LABEL_COUNTER
706 && par_it->layout()->toclevel != Layout::NOT_IN_TOC) {
707 buffer.tocBackend().updateItem(par_it);
708 buffer.structureChanged();