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 "vc-backend.h"
38 #include "frontends/Alert.h"
40 #include "insets/insetbibitem.h"
42 #include "support/filetools.h"
43 #include "support/fs_extras.h"
44 #include "support/lyxlib.h"
48 #include <boost/bind.hpp>
49 #include <boost/filesystem/operations.hpp>
55 using lyx::support::bformat;
56 using lyx::support::libFileSearch;
57 using lyx::support::makeDisplayPath;
58 using lyx::support::onlyFilename;
59 using lyx::support::onlyPath;
60 using lyx::support::unlink;
65 namespace fs = boost::filesystem;
67 extern BufferList bufferlist;
71 bool readFile(Buffer * const b, string const & s)
75 // File information about normal file
77 docstring const file = makeDisplayPath(s, 50);
78 docstring text = bformat(_("The specified document\n%1$s"
79 "\ncould not be read."), file);
80 Alert::error(_("Could not read document"), text);
84 // Check if emergency save file exists and is newer.
85 string const e = onlyPath(s) + onlyFilename(s) + ".emergency";
87 if (fs::exists(e) && fs::exists(s)
88 && fs::last_write_time(e) > fs::last_write_time(s))
90 docstring const file = makeDisplayPath(s, 20);
91 docstring const text =
92 bformat(_("An emergency save of the document "
94 "Recover emergency save?"), file);
95 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
96 _("&Recover"), _("&Load Original"),
100 // the file is not saved if we load the emergency file.
102 return b->readFile(e);
110 // Now check if autosave file is newer.
111 string const a = onlyPath(s) + '#' + onlyFilename(s) + '#';
113 if (fs::exists(a) && fs::exists(s)
114 && fs::last_write_time(a) > fs::last_write_time(s))
116 docstring const file = makeDisplayPath(s, 20);
117 docstring const text =
118 bformat(_("The backup of the document "
119 "%1$s is newer.\n\nLoad the "
120 "backup instead?"), file);
121 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
122 _("&Load backup"), _("Load &original"),
126 // the file is not saved if we load the autosave file.
128 return b->readFile(a);
130 // Here we delete the autosave
137 return b->readFile(s);
145 bool loadLyXFile(Buffer * b, string const & s)
149 if (fs::is_readable(s)) {
150 if (readFile(b, s)) {
151 b->lyxvc().file_found_hook(s);
152 if (!fs::is_writable(s))
153 b->setReadonly(true);
157 docstring const file = makeDisplayPath(s, 20);
158 // Here we probably should run
159 if (LyXVC::file_not_found_hook(s)) {
160 docstring const text =
161 bformat(_("Do you want to retrieve the document"
162 " %1$s from version control?"), file);
163 int const ret = Alert::prompt(_("Retrieve from version control?"),
164 text, 0, 1, _("&Retrieve"), _("&Cancel"));
167 // How can we know _how_ to do the checkout?
168 // With the current VC support it has to be,
169 // a RCS file since CVS do not have special ,v files.
171 return loadLyXFile(b, s);
179 Buffer * newFile(string const & filename, string const & templatename,
183 Buffer * b = bufferlist.newBuffer(filename);
187 // use defaults.lyx as a default template if it exists.
188 if (templatename.empty())
189 tname = libFileSearch("templates", "defaults.lyx");
191 tname = templatename;
193 if (!tname.empty()) {
194 if (!b->readFile(tname)) {
195 docstring const file = makeDisplayPath(tname, 50);
196 docstring const text = bformat(
197 _("The specified document template\n%1$s\ncould not be read."),
199 Alert::error(_("Could not read template"), text);
200 bufferlist.release(b);
207 b->setFileName(filename);
210 b->setReadonly(false);
211 b->fully_loaded(true);
212 b->updateDocLang(b->params().language);
218 void bufferErrors(Buffer const & buf, TeXErrors const & terr,
219 ErrorList & errorList)
221 TeXErrors::Errors::const_iterator cit = terr.begin();
222 TeXErrors::Errors::const_iterator end = terr.end();
224 for (; cit != end; ++cit) {
227 int errorrow = cit->error_in_line;
228 bool found = buf.texrow().getIdFromRow(errorrow, id_start,
234 found = buf.texrow().getIdFromRow(errorrow, id_end,
236 } while (found && id_start == id_end && pos_start == pos_end);
238 errorList.push_back(ErrorItem(lyx::from_utf8(cit->error_desc),
239 lyx::from_utf8(cit->error_text), id_start, pos_start, pos_end));
244 string const bufferFormat(Buffer const & buffer)
246 if (buffer.isDocBook())
248 else if (buffer.isLiterate())
255 int countWords(DocIterator const & from, DocIterator const & to)
259 for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
260 // Copied and adapted from isLetter() in ControlSpellChecker
262 && dit.pos() != dit.lastpos()
263 && dit.paragraph().isLetter(dit.pos())
264 && !isDeletedText(dit.paragraph(), dit.pos())) {
279 lyx::depth_type getDepth(DocIterator const & it)
281 lyx::depth_type depth = 0;
282 for (size_t i = 0 ; i < it.depth() ; ++i)
283 if (!it[i].inset().inMathed())
284 depth += it[i].paragraph().getDepth() + 1;
285 // remove 1 since the outer inset does not count
289 lyx::depth_type getItemDepth(ParIterator const & it)
291 Paragraph const & par = *it;
292 LYX_LABEL_TYPES const labeltype = par.layout()->labeltype;
294 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
297 // this will hold the lowest depth encountered up to now.
298 lyx::depth_type min_depth = getDepth(it);
299 ParIterator prev_it = it;
302 --prev_it.top().pit();
304 // start of nested inset: go to outer par
306 if (prev_it.empty()) {
307 // start of document: nothing to do
312 // We search for the first paragraph with same label
313 // that is not more deeply nested.
314 Paragraph & prev_par = *prev_it;
315 lyx::depth_type const prev_depth = getDepth(prev_it);
316 if (labeltype == prev_par.layout()->labeltype) {
317 if (prev_depth < min_depth) {
318 return prev_par.itemdepth + 1;
320 else if (prev_depth == min_depth) {
321 return prev_par.itemdepth;
324 min_depth = std::min(min_depth, prev_depth);
325 // small optimization: if we are at depth 0, we won't
326 // find anything else
327 if (prev_depth == 0) {
334 bool needEnumCounterReset(ParIterator const & it)
336 Paragraph const & par = *it;
337 BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
338 lyx::depth_type const cur_depth = par.getDepth();
339 ParIterator prev_it = it;
340 while (prev_it.pit()) {
341 --prev_it.top().pit();
342 Paragraph const & prev_par = *prev_it;
343 if (prev_par.getDepth() <= cur_depth)
344 return prev_par.layout()->labeltype != LABEL_ENUMERATE;
346 // start of nested inset: reset
351 // set the label of a paragraph. This includes the counters.
352 void setLabel(Buffer const & buf, ParIterator & it)
354 Paragraph & par = *it;
355 BufferParams const & bufparams = buf.params();
356 LyXTextClass const & textclass = bufparams.getLyXTextClass();
357 LyXLayout_ptr const & layout = par.layout();
358 Counters & counters = textclass.counters();
361 par.params().appendix(par.params().startOfAppendix());
363 par.params().appendix(it.plist()[it.pit() - 1].params().appendix());
364 if (!par.params().appendix() &&
365 par.params().startOfAppendix()) {
366 par.params().appendix(true);
367 textclass.counters().reset();
371 // Compute the item depth of the paragraph
372 par.itemdepth = getItemDepth(it);
374 // erase what was there before
375 par.params().labelString(string());
377 if (layout->margintype == MARGIN_MANUAL) {
378 if (par.params().labelWidthString().empty())
379 par.setLabelWidthString(layout->labelstring());
381 par.setLabelWidthString(string());
384 // is it a layout that has an automatic label?
385 if (layout->labeltype == LABEL_COUNTER) {
386 if (layout->toclevel <= buf.params().secnumdepth
387 && (layout->latextype != LATEX_ENVIRONMENT
388 || isFirstInSequence(it.pit(), it.plist()))) {
389 counters.step(layout->counter);
390 string label = expandLabel(buf, layout,
391 par.params().appendix());
392 par.params().labelString(label);
394 } else if (layout->labeltype == LABEL_ITEMIZE) {
395 // At some point of time we should do something more
396 // clever here, like:
397 // par.params().labelString(
398 // bufparams.user_defined_bullet(par.itemdepth).getText());
399 // for now, use a simple hardcoded label
401 switch (par.itemdepth) {
416 par.params().labelString(itemlabel);
417 } else if (layout->labeltype == LABEL_ENUMERATE) {
419 // Yes I know this is a really, really! bad solution
421 string enumcounter = "enum";
423 switch (par.itemdepth) {
435 // not a valid enumdepth...
439 // Maybe we have to reset the enumeration counter.
440 if (needEnumCounterReset(it))
441 counters.reset(enumcounter);
443 counters.step(enumcounter);
447 switch (par.itemdepth) {
449 format = N_("\\arabic{enumi}.");
452 format = N_("(\\alph{enumii})");
455 format = N_("\\roman{enumiii}.");
458 format = N_("\\Alph{enumiv}.");
461 // not a valid enumdepth...
466 par.params().labelString(counters.counterLabel(lyx::to_utf8(buf.B_(format))));
467 } else if (layout->labeltype == LABEL_BIBLIO) {// ale970302
468 counters.step("bibitem");
469 int number = counters.value("bibitem");
471 par.bibitem()->setCounter(number);
473 par.params().labelString(lyx::to_utf8(buf.B_(layout->labelstring())));
474 // In biblio should't be following counters but...
475 } else if (layout->labeltype == LABEL_SENSITIVE) {
476 // Search for the first float or wrap inset in the iterator
478 size_t i = it.depth();
481 InsetBase * const in = &it[i].inset();
482 if (in->lyxCode() == InsetBase::FLOAT_CODE
483 || in->lyxCode() == InsetBase::WRAP_CODE) {
484 type = in->getInsetName();
491 Floating const & fl = textclass.floats().getType(type);
493 counters.step(fl.type());
495 // Doesn't work... yet.
497 s = bformat(_("%1$s #:"), buf.B_(fl.name()));
499 // par->SetLayout(0);
501 s = buf.B_(layout->labelstring());
504 par.params().labelString(lyx::to_utf8(s));
505 } else if (layout->labeltype == LABEL_NO_LABEL)
506 par.params().labelString(string());
509 par.params().labelString(lyx::to_utf8(buf.B_(layout->labelstring())));
515 bool updateCurrentLabel(Buffer const & buf,
518 if (it == par_iterator_end(buf.inset()))
521 // if (it.lastpit == 0 && LyXText::isMainText())
524 switch (it->layout()->labeltype) {
529 case LABEL_TOP_ENVIRONMENT:
530 case LABEL_CENTERED_TOP_ENVIRONMENT:
536 case LABEL_SENSITIVE:
538 // do more things with enumerate later
539 case LABEL_ENUMERATE:
543 // This is dead code which get rid of a warning:
548 void updateLabels(Buffer const & buf,
549 ParIterator & from, ParIterator & to)
551 for (ParIterator it = from; it != to; ++it) {
552 if (it.pit() > it.lastpit())
554 if (!updateCurrentLabel (buf, it)) {
562 void updateLabels(Buffer const & buf,
565 if (updateCurrentLabel(buf, iter))
572 void updateLabels(Buffer const & buf)
574 // start over the counters
575 buf.params().getLyXTextClass().counters().reset();
577 ParIterator const end = par_iterator_end(buf.inset());
579 for (ParIterator it = par_iterator_begin(buf.inset()); it != end; ++it) {
580 // reduce depth if necessary
582 Paragraph const & prevpar = it.plist()[it.pit() - 1];
583 it->params().depth(min(it->params().depth(),
584 prevpar.getMaxDepthAfter()));
586 it->params().depth(0);
588 // set the counter for this paragraph
592 lyx::toc::updateToc(buf);
596 string expandLabel(Buffer const & buf,
597 LyXLayout_ptr const & layout, bool appendix)
599 LyXTextClass const & tclass = buf.params().getLyXTextClass();
602 string fmt = lyx::to_utf8(buf.B_(appendix ? layout->labelstring_appendix()
603 : layout->labelstring()));
605 // handle 'inherited level parts' in 'fmt',
606 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
607 size_t const i = fmt.find('@', 0);
608 if (i != string::npos) {
609 size_t const j = fmt.find('@', i + 1);
610 if (j != string::npos) {
611 string parent(fmt, i + 1, j - i - 1);
612 string label = expandLabel(buf, tclass[parent], appendix);
613 fmt = string(fmt, 0, i) + label + string(fmt, j + 1, string::npos);
617 return tclass.counters().counterLabel(fmt);