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 "lyxtextclass.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 "vc-backend.h"
38 #include "frontends/Alert.h"
40 #include "insets/insetbibitem.h"
41 #include "insets/insetcaption.h"
42 #include "insets/insetinclude.h"
44 #include "support/filetools.h"
45 #include "support/fs_extras.h"
46 #include "support/lyxlib.h"
48 #include <boost/bind.hpp>
49 #include <boost/filesystem/operations.hpp>
56 using support::bformat;
57 using support::FileName;
58 using support::libFileSearch;
59 using support::makeAbsPath;
60 using support::makeDisplayPath;
61 using support::onlyFilename;
62 using support::onlyPath;
63 using support::unlink;
68 namespace Alert = frontend::Alert;
69 namespace fs = boost::filesystem;
73 bool readFile(Buffer * const b, FileName const & s)
77 // File information about normal file
78 if (!fs::exists(s.toFilesystemEncoding())) {
79 docstring const file = makeDisplayPath(s.absFilename(), 50);
80 docstring text = bformat(_("The specified document\n%1$s"
81 "\ncould not be read."), file);
82 Alert::error(_("Could not read document"), text);
86 // Check if emergency save file exists and is newer.
87 FileName const e(s.absFilename() + ".emergency");
89 if (fs::exists(e.toFilesystemEncoding()) &&
90 fs::exists(s.toFilesystemEncoding()) &&
91 fs::last_write_time(e.toFilesystemEncoding()) > fs::last_write_time(s.toFilesystemEncoding()))
93 docstring const file = makeDisplayPath(s.absFilename(), 20);
94 docstring const text =
95 bformat(_("An emergency save of the document "
97 "Recover emergency save?"), file);
98 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
99 _("&Recover"), _("&Load Original"),
103 // the file is not saved if we load the emergency file.
105 return b->readFile(e);
113 // Now check if autosave file is newer.
114 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
116 if (fs::exists(a.toFilesystemEncoding()) &&
117 fs::exists(s.toFilesystemEncoding()) &&
118 fs::last_write_time(a.toFilesystemEncoding()) > fs::last_write_time(s.toFilesystemEncoding()))
120 docstring const file = makeDisplayPath(s.absFilename(), 20);
121 docstring const text =
122 bformat(_("The backup of the document "
123 "%1$s is newer.\n\nLoad the "
124 "backup instead?"), file);
125 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
126 _("&Load backup"), _("Load &original"),
130 // the file is not saved if we load the autosave file.
132 return b->readFile(a);
134 // Here we delete the autosave
141 return b->readFile(s);
149 bool loadLyXFile(Buffer * b, FileName const & s)
153 if (fs::is_readable(s.toFilesystemEncoding())) {
154 if (readFile(b, s)) {
155 b->lyxvc().file_found_hook(s);
156 if (!fs::is_writable(s.toFilesystemEncoding()))
157 b->setReadonly(true);
161 docstring const file = makeDisplayPath(s.absFilename(), 20);
162 // Here we probably should run
163 if (LyXVC::file_not_found_hook(s)) {
164 docstring const text =
165 bformat(_("Do you want to retrieve the document"
166 " %1$s from version control?"), file);
167 int const ret = Alert::prompt(_("Retrieve from version control?"),
168 text, 0, 1, _("&Retrieve"), _("&Cancel"));
171 // How can we know _how_ to do the checkout?
172 // With the current VC support it has to be,
173 // a RCS file since CVS do not have special ,v files.
175 return loadLyXFile(b, s);
182 // FIXME newFile() should probably be a member method of Application...
183 Buffer * newFile(string const & filename, string const & templatename,
187 Buffer * b = theBufferList().newBuffer(filename);
191 // use defaults.lyx as a default template if it exists.
192 if (templatename.empty())
193 tname = libFileSearch("templates", "defaults.lyx");
195 tname = makeAbsPath(templatename);
197 if (!tname.empty()) {
198 if (!b->readFile(tname)) {
199 docstring const file = makeDisplayPath(tname.absFilename(), 50);
200 docstring const text = bformat(
201 _("The specified document template\n%1$s\ncould not be read."),
203 Alert::error(_("Could not read template"), text);
204 theBufferList().release(b);
211 b->setFileName(filename);
214 b->setReadonly(false);
215 b->fully_loaded(true);
216 b->updateDocLang(b->params().language);
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(InsetBase & inset, Floating const & fl,
358 LyXText * text = inset.getText(0);
362 ParagraphList & pars = text->paragraphs();
367 docstring const counter = from_ascii(fl.type());
368 docstring const label = from_utf8(fl.name());
370 ParagraphList::iterator p = pars.begin();
371 for (; p != pars.end(); ++p) {
372 InsetList::iterator it2 = p->insetlist.begin();
373 InsetList::iterator end2 = p->insetlist.end();
374 // Any caption within this float should have the same
375 // label prefix but different numbers.
376 for (; it2 != end2; ++it2) {
377 InsetBase & icap = *it2->inset;
378 // Look deeper just in case.
379 setCaptionLabels(icap, fl, counters);
380 if (icap.lyxCode() == InsetBase::CAPTION_CODE) {
381 // We found a caption!
382 counters.step(counter);
383 int number = counters.value(counter);
384 static_cast<InsetCaption &>(icap).setCount(number);
385 static_cast<InsetCaption &>(icap).setLabel(label);
392 void setCaptions(Paragraph & par, LyXTextClass 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 InsetBase & inset = *it->inset;
403 if (inset.lyxCode() != InsetBase::FLOAT_CODE
404 && inset.lyxCode() != InsetBase::WRAP_CODE)
407 docstring const & type = inset.getInsetName();
411 Floating const & fl = textclass.floats().getType(to_ascii(type));
412 setCaptionLabels(inset, fl, counters);
416 // set the label of a paragraph. This includes the counters.
417 void setLabel(Buffer const & buf, ParIterator & it, LyXTextClass const & textclass)
419 Paragraph & par = *it;
420 LyXLayout_ptr const & layout = par.layout();
421 Counters & counters = textclass.counters();
424 par.params().appendix(par.params().startOfAppendix());
426 par.params().appendix(it.plist()[it.pit() - 1].params().appendix());
427 if (!par.params().appendix() &&
428 par.params().startOfAppendix()) {
429 par.params().appendix(true);
430 textclass.counters().reset();
434 // Compute the item depth of the paragraph
435 par.itemdepth = getItemDepth(it);
437 if (layout->margintype == MARGIN_MANUAL) {
438 if (par.params().labelWidthString().empty())
439 par.params().labelWidthString(par.translateIfPossible(layout->labelstring(), buf.params()));
441 par.params().labelWidthString(docstring());
444 // Optimisation: setLabel() can be called for each for each
445 // paragraph of the document. So we make the string static to
446 // avoid the repeated instanciation.
447 static docstring itemlabel;
449 // is it a layout that has an automatic label?
450 if (layout->labeltype == LABEL_COUNTER) {
451 if (layout->toclevel <= buf.params().secnumdepth
452 && (layout->latextype != LATEX_ENVIRONMENT
453 || isFirstInSequence(it.pit(), it.plist()))) {
454 counters.step(layout->counter);
455 par.params().labelString(
456 par.expandLabel(layout, buf.params()));
458 par.params().labelString(docstring());
460 } else if (layout->labeltype == LABEL_ITEMIZE) {
461 // At some point of time we should do something more
462 // clever here, like:
463 // par.params().labelString(
464 // buf.params().user_defined_bullet(par.itemdepth).getText());
465 // for now, use a simple hardcoded label
466 switch (par.itemdepth) {
468 itemlabel = char_type(0x2022);
471 itemlabel = char_type(0x2013);
474 itemlabel = char_type(0x2217);
477 itemlabel = char_type(0x2219); // or 0x00b7
480 par.params().labelString(itemlabel);
482 } else if (layout->labeltype == LABEL_ENUMERATE) {
484 // Yes I know this is a really, really! bad solution
486 docstring enumcounter = from_ascii("enum");
488 switch (par.itemdepth) {
500 // not a valid enumdepth...
504 // Maybe we have to reset the enumeration counter.
505 if (needEnumCounterReset(it))
506 counters.reset(enumcounter);
508 counters.step(enumcounter);
512 switch (par.itemdepth) {
514 format = N_("\\arabic{enumi}.");
517 format = N_("(\\alph{enumii})");
520 format = N_("\\roman{enumiii}.");
523 format = N_("\\Alph{enumiv}.");
526 // not a valid enumdepth...
530 par.params().labelString(counters.counterLabel(
531 par.translateIfPossible(from_ascii(format), buf.params())));
533 } else if (layout->labeltype == LABEL_BIBLIO) {// ale970302
534 counters.step(from_ascii("bibitem"));
535 int number = counters.value(from_ascii("bibitem"));
537 par.bibitem()->setCounter(number);
539 par.params().labelString(
540 par.translateIfPossible(layout->labelstring(), buf.params()));
541 // In biblio shouldn't be following counters but...
542 } else if (layout->labeltype == LABEL_SENSITIVE) {
543 // Search for the first float or wrap inset in the iterator
544 size_t i = it.depth();
549 if (in->lyxCode() == InsetBase::FLOAT_CODE
550 || in->lyxCode() == InsetBase::WRAP_CODE)
553 docstring const & type = in->getInsetName();
556 Floating const & fl = textclass.floats().getType(to_ascii(type));
558 counters.step(from_ascii(fl.type()));
560 // Doesn't work... yet.
561 par.params().labelString(par.translateIfPossible(
562 bformat(from_ascii("%1$s #:"), from_utf8(fl.name())),
565 // par->SetLayout(0);
566 par.params().labelString(par.translateIfPossible(
567 layout->labelstring(), buf.params()));
570 } else if (layout->labeltype == LABEL_NO_LABEL)
571 par.params().labelString(docstring());
573 par.params().labelString(
574 par.translateIfPossible(layout->labelstring(), buf.params()));
580 bool updateCurrentLabel(Buffer const & buf,
583 if (it == par_iterator_end(buf.inset()))
586 // if (it.lastpit == 0 && LyXText::isMainText(buf))
589 switch (it->layout()->labeltype) {
594 case LABEL_TOP_ENVIRONMENT:
595 case LABEL_CENTERED_TOP_ENVIRONMENT:
598 setLabel(buf, it, buf.params().getLyXTextClass());
601 case LABEL_SENSITIVE:
603 // do more things with enumerate later
604 case LABEL_ENUMERATE:
608 // This is dead code which get rid of a warning:
613 void updateLabels(Buffer const & buf,
614 ParIterator & from, ParIterator & to, bool childonly)
616 for (ParIterator it = from; it != to; ++it) {
617 if (it.pit() > it.lastpit())
619 if (!updateCurrentLabel (buf, it)) {
620 updateLabels(buf, childonly);
627 void updateLabels(Buffer const & buf, ParIterator & iter, bool childonly)
629 if (updateCurrentLabel(buf, iter))
632 updateLabels(buf, childonly);
636 void updateLabels(Buffer const & buf, bool childonly)
638 // Use the master text class also for child documents
639 LyXTextClass const & textclass = buf.params().getLyXTextClass();
642 // If this is a child document start with the master
643 Buffer const * const master = buf.getMasterBuffer();
644 if (master != &buf) {
645 updateLabels(*master);
649 // start over the counters
650 textclass.counters().reset();
653 ParIterator const end = par_iterator_end(buf.inset());
655 for (ParIterator it = par_iterator_begin(buf.inset()); it != end; ++it) {
656 // reduce depth if necessary
658 Paragraph const & prevpar = it.plist()[it.pit() - 1];
659 it->params().depth(min(it->params().depth(),
660 prevpar.getMaxDepthAfter()));
662 it->params().depth(0);
664 // set the counter for this paragraph
665 setLabel(buf, it, textclass);
667 // It is better to set the captions after setLabel because
668 // the caption number might need the section number in the
670 setCaptions(*it, textclass);
673 InsetList::const_iterator iit = it->insetlist.begin();
674 InsetList::const_iterator end = it->insetlist.end();
675 for (; iit != end; ++iit) {
676 if (iit->inset->lyxCode() == InsetBase::INCLUDE_CODE)
677 static_cast<InsetInclude const *>(iit->inset)
682 const_cast<Buffer &>(buf).tocBackend().update();