]> git.lyx.org Git - lyx.git/blob - src/buffer_funcs.C
0de992187c5a135520c022edfaa181bb3df799c6
[lyx.git] / src / buffer_funcs.C
1 /**
2  * \file buffer_funcs.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Alfredo Braunstein
8  *
9  * Full author contact details are available in file CREDITS.
10  *
11  */
12
13 #include <config.h>
14
15 #include "buffer_funcs.h"
16 #include "buffer.h"
17 #include "bufferlist.h"
18 #include "bufferparams.h"
19 #include "dociterator.h"
20 #include "counters.h"
21 #include "errorlist.h"
22 #include "Floating.h"
23 #include "FloatList.h"
24 #include "gettext.h"
25 #include "language.h"
26 #include "LaTeX.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"
33 #include "lyxvc.h"
34 #include "texrow.h"
35 #include "vc-backend.h"
36 #include "toc.h"
37
38 #include "frontends/Alert.h"
39
40 #include "insets/insetbibitem.h"
41
42 #include "support/filetools.h"
43 #include "support/fs_extras.h"
44 #include "support/lyxlib.h"
45
46 #include <iostream>
47
48 #include <boost/bind.hpp>
49 #include <boost/filesystem/operations.hpp>
50
51 using namespace std;
52
53 using lyx::pit_type;
54 using lyx::support::bformat;
55 using lyx::support::libFileSearch;
56 using lyx::support::makeDisplayPath;
57 using lyx::support::onlyFilename;
58 using lyx::support::onlyPath;
59 using lyx::support::unlink;
60
61 using std::min;
62 using std::string;
63
64 namespace fs = boost::filesystem;
65
66 extern BufferList bufferlist;
67
68 namespace {
69
70 bool readFile(Buffer * const b, string const & s)
71 {
72         BOOST_ASSERT(b);
73
74         // File information about normal file
75         if (!fs::exists(s)) {
76                 string const file = makeDisplayPath(s, 50);
77                 string text = bformat(lyx::to_utf8(_("The specified document\n%1$s"
78                                                      "\ncould not be read.")), file);
79                 Alert::error(lyx::to_utf8(_("Could not read document")), text);
80                 return false;
81         }
82
83         // Check if emergency save file exists and is newer.
84         string const e = onlyPath(s) + onlyFilename(s) + ".emergency";
85
86         if (fs::exists(e) && fs::exists(s)
87             && fs::last_write_time(e) > fs::last_write_time(s))
88         {
89                 string const file = makeDisplayPath(s, 20);
90                 string const text =
91                         bformat(lyx::to_utf8(_("An emergency save of the document "
92                                   "%1$s exists.\n\n"
93                                                "Recover emergency save?")), file);
94                 switch (Alert::prompt(lyx::to_utf8(_("Load emergency save?")), text, 0, 2,
95                                       lyx::to_utf8(_("&Recover")),  lyx::to_utf8(_("&Load Original")),
96                                       lyx::to_utf8(_("&Cancel"))))
97                 {
98                 case 0:
99                         // the file is not saved if we load the emergency file.
100                         b->markDirty();
101                         return b->readFile(e);
102                 case 1:
103                         break;
104                 default:
105                         return false;
106                 }
107         }
108
109         // Now check if autosave file is newer.
110         string const a = onlyPath(s) + '#' + onlyFilename(s) + '#';
111
112         if (fs::exists(a) && fs::exists(s)
113             && fs::last_write_time(a) > fs::last_write_time(s))
114         {
115                 string const file = makeDisplayPath(s, 20);
116                 string const text =
117                         bformat(lyx::to_utf8(_("The backup of the document "
118                                   "%1$s is newer.\n\nLoad the "
119                                                "backup instead?")), file);
120                 switch (Alert::prompt(lyx::to_utf8(_("Load backup?")), text, 0, 2,
121                                       lyx::to_utf8(_("&Load backup")), lyx::to_utf8(_("Load &original")),
122                                       lyx::to_utf8(_("&Cancel") )))
123                 {
124                 case 0:
125                         // the file is not saved if we load the autosave file.
126                         b->markDirty();
127                         return b->readFile(a);
128                 case 1:
129                         // Here we delete the autosave
130                         unlink(a);
131                         break;
132                 default:
133                         return false;
134                 }
135         }
136         return b->readFile(s);
137 }
138
139
140 } // namespace anon
141
142
143
144 bool loadLyXFile(Buffer * b, string const & s)
145 {
146         BOOST_ASSERT(b);
147
148         if (fs::is_readable(s)) {
149                 if (readFile(b, s)) {
150                         b->lyxvc().file_found_hook(s);
151                         if (!fs::is_writable(s))
152                                 b->setReadonly(true);
153                         return true;
154                 }
155         } else {
156                 string const file = makeDisplayPath(s, 20);
157                 // Here we probably should run
158                 if (LyXVC::file_not_found_hook(s)) {
159                         string const text =
160                                 bformat(lyx::to_utf8(_("Do you want to retrieve the document"
161                                                        " %1$s from version control?")), file);
162                         int const ret = Alert::prompt(lyx::to_utf8(_("Retrieve from version control?")),
163                                 text, 0, 1, lyx::to_utf8(_("&Retrieve")), lyx::to_utf8(_("&Cancel")));
164
165                         if (ret == 0) {
166                                 // How can we know _how_ to do the checkout?
167                                 // With the current VC support it has to be,
168                                 // a RCS file since CVS do not have special ,v files.
169                                 RCS::retrieve(s);
170                                 return loadLyXFile(b, s);
171                         }
172                 }
173         }
174         return false;
175 }
176
177
178 Buffer * newFile(string const & filename, string const & templatename,
179                  bool const isNamed)
180 {
181         // get a free buffer
182         Buffer * b = bufferlist.newBuffer(filename);
183         BOOST_ASSERT(b);
184
185         string tname;
186         // use defaults.lyx as a default template if it exists.
187         if (templatename.empty())
188                 tname = libFileSearch("templates", "defaults.lyx");
189         else
190                 tname = templatename;
191
192         if (!tname.empty()) {
193                 if (!b->readFile(tname)) {
194                         string const file = makeDisplayPath(tname, 50);
195                         string const text  = bformat(lyx::to_utf8(_("The specified document template\n%1$s\ncould not be read.")), file);
196                         Alert::error(lyx::to_utf8(_("Could not read template")), text);
197                         bufferlist.release(b);
198                         return 0;
199                 }
200         }
201
202         if (!isNamed) {
203                 b->setUnnamed();
204                 b->setFileName(filename);
205         }
206
207         b->setReadonly(false);
208         b->fully_loaded(true);
209         b->updateDocLang(b->params().language);
210
211         return b;
212 }
213
214
215 void bufferErrors(Buffer const & buf, TeXErrors const & terr,
216                                   ErrorList & errorList)
217 {
218         TeXErrors::Errors::const_iterator cit = terr.begin();
219         TeXErrors::Errors::const_iterator end = terr.end();
220
221         for (; cit != end; ++cit) {
222                 int id_start = -1;
223                 int pos_start = -1;
224                 int errorrow = cit->error_in_line;
225                 bool found = buf.texrow().getIdFromRow(errorrow, id_start,
226                                                        pos_start);
227                 int id_end = -1;
228                 int pos_end = -1;
229                 do {
230                         ++errorrow;
231                         found = buf.texrow().getIdFromRow(errorrow, id_end,
232                                                           pos_end);
233                 } while (found && id_start == id_end && pos_start == pos_end);
234
235                 errorList.push_back(ErrorItem(cit->error_desc,
236                         cit->error_text, id_start, pos_start, pos_end));
237         }
238 }
239
240
241 string const bufferFormat(Buffer const & buffer)
242 {
243         if (buffer.isDocBook())
244                 return "docbook";
245         else if (buffer.isLiterate())
246                 return "literate";
247         else
248                 return "latex";
249 }
250
251
252 int countWords(DocIterator const & from, DocIterator const & to)
253 {
254         int count = 0;
255         bool inword = false;
256         for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
257                 // Copied and adapted from isLetter() in ControlSpellChecker
258                 if (dit.inTexted()
259                     && dit.pos() != dit.lastpos()
260                     && dit.paragraph().isLetter(dit.pos())
261                     && !isDeletedText(dit.paragraph(), dit.pos())) {
262                         if (!inword) {
263                                 ++count;
264                                 inword = true;
265                         }
266                 } else if (inword)
267                         inword = false;
268         }
269
270         return count;
271 }
272
273
274 namespace {
275
276 lyx::depth_type getDepth(DocIterator const & it)
277 {
278         lyx::depth_type depth = 0;
279         for (size_t i = 0 ; i < it.depth() ; ++i)
280                 if (!it[i].inset().inMathed())
281                         depth += it[i].paragraph().getDepth() + 1;
282         // remove 1 since the outer inset does not count
283         return depth - 1;
284 }
285
286 lyx::depth_type getItemDepth(ParIterator const & it)
287 {
288         Paragraph const & par = *it;
289         LYX_LABEL_TYPES const labeltype = par.layout()->labeltype;
290
291         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
292                 return 0;
293
294         // this will hold the lowest depth encountered up to now.
295         lyx::depth_type min_depth = getDepth(it);
296         ParIterator prev_it = it;
297         while (true) {
298                 if (prev_it.pit())
299                         --prev_it.top().pit();
300                 else {
301                         // start of nested inset: go to outer par
302                         prev_it.pop_back();
303                         if (prev_it.empty()) {
304                                 // start of document: nothing to do
305                                 return 0;
306                         }
307                 }
308
309                 // We search for the first paragraph with same label
310                 // that is not more deeply nested.
311                 Paragraph & prev_par = *prev_it;
312                 lyx::depth_type const prev_depth = getDepth(prev_it);
313                 if (labeltype == prev_par.layout()->labeltype) {
314                         if (prev_depth < min_depth) {
315                                 return prev_par.itemdepth + 1;
316                         }
317                         else if (prev_depth == min_depth) {
318                                 return prev_par.itemdepth;
319                         }
320                 }
321                 min_depth = std::min(min_depth, prev_depth);
322                 // small optimization: if we are at depth 0, we won't
323                 // find anything else
324                 if (prev_depth == 0) {
325                         return 0;
326                 }
327         }
328 }
329
330
331 bool needEnumCounterReset(ParIterator const & it)
332 {
333         Paragraph const & par = *it;
334         BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
335         lyx::depth_type const cur_depth = par.getDepth();
336         ParIterator prev_it = it;
337         while (prev_it.pit()) {
338                 --prev_it.top().pit();
339                 Paragraph const & prev_par = *prev_it;
340                 if (prev_par.getDepth() <= cur_depth)
341                         return  prev_par.layout()->labeltype != LABEL_ENUMERATE;
342         }
343         // start of nested inset: reset
344         return true;
345 }
346
347
348 // set the label of a paragraph. This includes the counters.
349 void setLabel(Buffer const & buf, ParIterator & it)
350 {
351         Paragraph & par = *it;
352         BufferParams const & bufparams = buf.params();
353         LyXTextClass const & textclass = bufparams.getLyXTextClass();
354         LyXLayout_ptr const & layout = par.layout();
355         Counters & counters = textclass.counters();
356
357         if (it.pit() == 0) {
358                 par.params().appendix(par.params().startOfAppendix());
359         } else {
360                 par.params().appendix(it.plist()[it.pit() - 1].params().appendix());
361                 if (!par.params().appendix() &&
362                     par.params().startOfAppendix()) {
363                         par.params().appendix(true);
364                         textclass.counters().reset();
365                 }
366         }
367
368         // Compute the item depth of the paragraph
369         par.itemdepth = getItemDepth(it);
370
371         // erase what was there before
372         par.params().labelString(string());
373
374         if (layout->margintype == MARGIN_MANUAL) {
375                 if (par.params().labelWidthString().empty())
376                         par.setLabelWidthString(layout->labelstring());
377         } else {
378                 par.setLabelWidthString(string());
379         }
380
381         // is it a layout that has an automatic label?
382         if (layout->labeltype == LABEL_COUNTER) {
383                 if (layout->toclevel <= buf.params().secnumdepth
384                     && (layout->latextype != LATEX_ENVIRONMENT
385                         || isFirstInSequence(it.pit(), it.plist()))) {
386                         counters.step(layout->counter);
387                         string label = expandLabel(buf, layout,
388                                                    par.params().appendix());
389                         par.params().labelString(label);
390                 }
391         } else if (layout->labeltype == LABEL_ITEMIZE) {
392                 // At some point of time we should do something more
393                 // clever here, like:
394                 //   par.params().labelString(
395                 //    bufparams.user_defined_bullet(par.itemdepth).getText());
396                 // for now, use a simple hardcoded label
397                 string itemlabel;
398                 switch (par.itemdepth) {
399                 case 0:
400                         itemlabel = "*";
401                         break;
402                 case 1:
403                         itemlabel = "-";
404                         break;
405                 case 2:
406                         itemlabel = "@";
407                         break;
408                 case 3:
409                         itemlabel = "·";
410                         break;
411                 }
412
413                 par.params().labelString(itemlabel);
414         } else if (layout->labeltype == LABEL_ENUMERATE) {
415                 // FIXME
416                 // Yes I know this is a really, really! bad solution
417                 // (Lgb)
418                 string enumcounter = "enum";
419
420                 switch (par.itemdepth) {
421                 case 2:
422                         enumcounter += 'i';
423                 case 1:
424                         enumcounter += 'i';
425                 case 0:
426                         enumcounter += 'i';
427                         break;
428                 case 3:
429                         enumcounter += "iv";
430                         break;
431                 default:
432                         // not a valid enumdepth...
433                         break;
434                 }
435
436                 // Maybe we have to reset the enumeration counter.
437                 if (needEnumCounterReset(it))
438                         counters.reset(enumcounter);
439
440                 counters.step(enumcounter);
441
442                 string format;
443
444                 switch (par.itemdepth) {
445                 case 0:
446                         format = N_("\\arabic{enumi}.");
447                         break;
448                 case 1:
449                         format = N_("(\\alph{enumii})");
450                         break;
451                 case 2:
452                         format = N_("\\roman{enumiii}.");
453                         break;
454                 case 3:
455                         format = N_("\\Alph{enumiv}.");
456                         break;
457                 default:
458                         // not a valid enumdepth...
459                         break;
460                 }
461
462                 // FIXME UNICODE
463                 par.params().labelString(counters.counterLabel(lyx::to_utf8(buf.B_(format))));
464         } else if (layout->labeltype == LABEL_BIBLIO) {// ale970302
465                 counters.step("bibitem");
466                 int number = counters.value("bibitem");
467                 if (par.bibitem())
468                         par.bibitem()->setCounter(number);
469                 // FIXME UNICODE
470                 par.params().labelString(lyx::to_utf8(buf.B_(layout->labelstring())));
471                 // In biblio should't be following counters but...
472         } else if (layout->labeltype == LABEL_SENSITIVE) {
473                 // Search for the first float or wrap inset in the iterator
474                 string type;
475                 size_t i = it.depth();
476                 while (i > 0) {
477                         --i;
478                         InsetBase * const in = &it[i].inset();
479                         if (in->lyxCode() == InsetBase::FLOAT_CODE
480                             || in->lyxCode() == InsetBase::WRAP_CODE) {
481                                 type = in->getInsetName();
482                                 break;
483                         }
484                 }
485
486                 string s;
487                 if (!type.empty()) {
488                         Floating const & fl = textclass.floats().getType(type);
489
490                         counters.step(fl.type());
491
492                         // Doesn't work... yet.
493                         // FIXME UNICODE
494                         s = bformat(lyx::to_utf8(_("%1$s #:")), lyx::to_utf8(buf.B_(fl.name())));
495                 } else {
496                         // par->SetLayout(0);
497                         // FIXME UNICODE
498                         s = lyx::to_utf8(buf.B_(layout->labelstring()));
499                 }
500
501                 par.params().labelString(s);
502         } else if (layout->labeltype == LABEL_NO_LABEL)
503                 par.params().labelString(string());
504         else
505                 // FIXME UNICODE
506                 par.params().labelString(lyx::to_utf8(buf.B_(layout->labelstring())));
507 }
508
509 } // anon namespace
510
511
512 bool updateCurrentLabel(Buffer const & buf,
513         ParIterator & it)
514 {
515     if (it == par_iterator_end(buf.inset()))
516         return false;
517
518 //      if (it.lastpit == 0 && LyXText::isMainText())
519 //              return false;
520
521         switch (it->layout()->labeltype) {
522
523         case LABEL_NO_LABEL:
524         case LABEL_MANUAL:
525         case LABEL_BIBLIO:
526         case LABEL_TOP_ENVIRONMENT:
527         case LABEL_CENTERED_TOP_ENVIRONMENT:
528         case LABEL_STATIC:
529         case LABEL_ITEMIZE:
530                 setLabel(buf, it);
531                 return true;
532
533         case LABEL_SENSITIVE:
534         case LABEL_COUNTER:
535         // do more things with enumerate later
536         case LABEL_ENUMERATE:
537                 return false;
538         }
539
540         // This is dead code which get rid of a warning:
541         return true;
542 }
543
544
545 void updateLabels(Buffer const & buf,
546         ParIterator & from, ParIterator & to)
547 {
548         for (ParIterator it = from; it != to; ++it) {
549                 if (it.pit() > it.lastpit())
550                         return;
551                 if (!updateCurrentLabel (buf, it)) {
552                         updateLabels(buf);
553                         return;
554                 }
555         }
556 }
557
558
559 void updateLabels(Buffer const & buf,
560         ParIterator & iter)
561 {
562         if (updateCurrentLabel(buf, iter))
563                 return;
564
565         updateLabels(buf);
566 }
567
568
569 void updateLabels(Buffer const & buf)
570 {
571         // start over the counters
572         buf.params().getLyXTextClass().counters().reset();
573
574         ParIterator const end = par_iterator_end(buf.inset());
575
576         for (ParIterator it = par_iterator_begin(buf.inset()); it != end; ++it) {
577                 // reduce depth if necessary
578                 if (it.pit()) {
579                         Paragraph const & prevpar = it.plist()[it.pit() - 1];
580                         it->params().depth(min(it->params().depth(),
581                                                prevpar.getMaxDepthAfter()));
582                 } else
583                         it->params().depth(0);
584
585                 // set the counter for this paragraph
586                 setLabel(buf, it);
587         }
588
589         lyx::toc::updateToc(buf);
590 }
591
592
593 string expandLabel(Buffer const & buf,
594         LyXLayout_ptr const & layout, bool appendix)
595 {
596         LyXTextClass const & tclass = buf.params().getLyXTextClass();
597
598         // FIXME UNICODE
599         string fmt = lyx::to_utf8(buf.B_(appendix ? layout->labelstring_appendix()
600                                   : layout->labelstring()));
601
602         // handle 'inherited level parts' in 'fmt',
603         // i.e. the stuff between '@' in   '@Section@.\arabic{subsection}'
604         size_t const i = fmt.find('@', 0);
605         if (i != string::npos) {
606                 size_t const j = fmt.find('@', i + 1);
607                 if (j != string::npos) {
608                         string parent(fmt, i + 1, j - i - 1);
609                         string label = expandLabel(buf, tclass[parent], appendix);
610                         fmt = string(fmt, 0, i) + label + string(fmt, j + 1, string::npos);
611                 }
612         }
613
614         return tclass.counters().counterLabel(fmt);
615 }