]> git.lyx.org Git - lyx.git/blob - src/buffer_funcs.cpp
SCons: msvc does not need this /TP option any more after we rename .C => .cpp. Also...
[lyx.git] / src / buffer_funcs.cpp
1 /**
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.
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 "debug.h"
20 #include "DocIterator.h"
21 #include "Counters.h"
22 #include "ErrorList.h"
23 #include "Floating.h"
24 #include "FloatList.h"
25 #include "gettext.h"
26 #include "InsetIterator.h"
27 #include "Language.h"
28 #include "LaTeX.h"
29 #include "LyX.h"
30 #include "TextClass.h"
31 #include "Paragraph.h"
32 #include "paragraph_funcs.h"
33 #include "ParagraphList.h"
34 #include "ParagraphParameters.h"
35 #include "ParIterator.h"
36 #include "LyXVC.h"
37 #include "TexRow.h"
38 #include "Text.h"
39 #include "TocBackend.h"
40 #include "VCBackend.h"
41
42 #include "frontends/alert.h"
43
44 #include "insets/InsetBibitem.h"
45 #include "insets/InsetInclude.h"
46
47 #include "support/filetools.h"
48 #include "support/fs_extras.h"
49 #include "support/lyxlib.h"
50
51 #include <boost/bind.hpp>
52 #include <boost/filesystem/operations.hpp>
53
54 using std::min;
55 using std::string;
56
57
58 namespace lyx {
59
60 using namespace std;
61
62 using support::bformat;
63 using support::FileName;
64 using support::libFileSearch;
65 using support::makeAbsPath;
66 using support::makeDisplayPath;
67 using support::onlyFilename;
68 using support::onlyPath;
69 using support::unlink;
70
71 namespace Alert = frontend::Alert;
72 namespace fs = boost::filesystem;
73
74 namespace {
75
76 bool readFile(Buffer * const b, FileName const & s)
77 {
78         BOOST_ASSERT(b);
79
80         // File information about normal file
81         if (!fs::exists(s.toFilesystemEncoding())) {
82                 docstring const file = makeDisplayPath(s.absFilename(), 50);
83                 docstring text = bformat(_("The specified document\n%1$s"
84                                                      "\ncould not be read."), file);
85                 Alert::error(_("Could not read document"), text);
86                 return false;
87         }
88
89         // Check if emergency save file exists and is newer.
90         FileName const e(s.absFilename() + ".emergency");
91
92         if (fs::exists(e.toFilesystemEncoding()) &&
93             fs::exists(s.toFilesystemEncoding()) &&
94             fs::last_write_time(e.toFilesystemEncoding()) > fs::last_write_time(s.toFilesystemEncoding()))
95         {
96                 docstring const file = makeDisplayPath(s.absFilename(), 20);
97                 docstring const text =
98                         bformat(_("An emergency save of the document "
99                                   "%1$s exists.\n\n"
100                                                "Recover emergency save?"), file);
101                 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
102                                       _("&Recover"),  _("&Load Original"),
103                                       _("&Cancel")))
104                 {
105                 case 0:
106                         // the file is not saved if we load the emergency file.
107                         b->markDirty();
108                         return b->readFile(e);
109                 case 1:
110                         break;
111                 default:
112                         return false;
113                 }
114         }
115
116         // Now check if autosave file is newer.
117         FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
118
119         if (fs::exists(a.toFilesystemEncoding()) &&
120             fs::exists(s.toFilesystemEncoding()) &&
121             fs::last_write_time(a.toFilesystemEncoding()) > fs::last_write_time(s.toFilesystemEncoding()))
122         {
123                 docstring const file = makeDisplayPath(s.absFilename(), 20);
124                 docstring const text =
125                         bformat(_("The backup of the document "
126                                   "%1$s is newer.\n\nLoad the "
127                                                "backup instead?"), file);
128                 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
129                                       _("&Load backup"), _("Load &original"),
130                                       _("&Cancel") ))
131                 {
132                 case 0:
133                         // the file is not saved if we load the autosave file.
134                         b->markDirty();
135                         return b->readFile(a);
136                 case 1:
137                         // Here we delete the autosave
138                         unlink(a);
139                         break;
140                 default:
141                         return false;
142                 }
143         }
144         return b->readFile(s);
145 }
146
147
148 } // namespace anon
149
150
151
152 bool loadLyXFile(Buffer * b, FileName const & s)
153 {
154         BOOST_ASSERT(b);
155
156         if (fs::is_readable(s.toFilesystemEncoding())) {
157                 if (readFile(b, s)) {
158                         b->lyxvc().file_found_hook(s);
159                         if (!fs::is_writable(s.toFilesystemEncoding()))
160                                 b->setReadonly(true);
161                         return true;
162                 }
163         } else {
164                 docstring const file = makeDisplayPath(s.absFilename(), 20);
165                 // Here we probably should run
166                 if (LyXVC::file_not_found_hook(s)) {
167                         docstring const text =
168                                 bformat(_("Do you want to retrieve the document"
169                                                        " %1$s from version control?"), file);
170                         int const ret = Alert::prompt(_("Retrieve from version control?"),
171                                 text, 0, 1, _("&Retrieve"), _("&Cancel"));
172
173                         if (ret == 0) {
174                                 // How can we know _how_ to do the checkout?
175                                 // With the current VC support it has to be,
176                                 // a RCS file since CVS do not have special ,v files.
177                                 RCS::retrieve(s);
178                                 return loadLyXFile(b, s);
179                         }
180                 }
181         }
182         return false;
183 }
184
185
186 bool checkIfLoaded(FileName const & fn)
187 {
188         return theBufferList().getBuffer(fn.absFilename());
189 }
190
191
192 Buffer * checkAndLoadLyXFile(FileName const & filename)
193 {
194         // File already open?
195         Buffer * checkBuffer = theBufferList().getBuffer(filename.absFilename());
196         if (checkBuffer) {
197                 if (checkBuffer->isClean())
198                         return checkBuffer;
199                 docstring const file = makeDisplayPath(filename.absFilename(), 20);
200                 docstring text = bformat(_(
201                                 "The document %1$s is already loaded and has unsaved changes.\n"
202                                 "Do you want to abandon your changes and reload the version on disk?"), file);
203                 if (Alert::prompt(_("Reload saved document?"),
204                                 text, 0, 1,  _("&Reload"), _("&Keep Changes")))
205                         return checkBuffer;
206
207                 // FIXME: should be LFUN_REVERT
208                 if (theBufferList().close(checkBuffer, false))
209                         // Load it again.
210                         return checkAndLoadLyXFile(filename);
211                 else
212                         // The file could not be closed.
213                         return 0;
214         }
215
216         if (isFileReadable(filename)) {
217                 Buffer * b = theBufferList().newBuffer(filename.absFilename());
218                 if (!lyx::loadLyXFile(b, filename)) {
219                         theBufferList().release(b);
220                         return 0;
221                 }
222                 return b;
223         }
224
225         docstring text = bformat(_("The document %1$s does not yet "
226                 "exist.\n\nDo you want to create a new document?"),
227                 from_utf8(filename.absFilename()));
228         if (!Alert::prompt(_("Create new document?"),
229                         text, 0, 1, _("&Create"), _("Cancel")))
230                 return newFile(filename.absFilename(), string(), true);
231
232         return 0;
233 }
234
235 // FIXME newFile() should probably be a member method of Application...
236 Buffer * newFile(string const & filename, string const & templatename,
237                  bool const isNamed)
238 {
239         // get a free buffer
240         Buffer * b = theBufferList().newBuffer(filename);
241         BOOST_ASSERT(b);
242
243         FileName tname;
244         // use defaults.lyx as a default template if it exists.
245         if (templatename.empty())
246                 tname = libFileSearch("templates", "defaults.lyx");
247         else
248                 tname = makeAbsPath(templatename);
249
250         if (!tname.empty()) {
251                 if (!b->readFile(tname)) {
252                         docstring const file = makeDisplayPath(tname.absFilename(), 50);
253                         docstring const text  = bformat(
254                                 _("The specified document template\n%1$s\ncould not be read."),
255                                 file);
256                         Alert::error(_("Could not read template"), text);
257                         theBufferList().release(b);
258                         return 0;
259                 }
260         }
261
262         if (!isNamed) {
263                 b->setUnnamed();
264                 b->setFileName(filename);
265         }
266
267         b->setReadonly(false);
268         b->fully_loaded(true);
269
270         return b;
271 }
272
273
274 void bufferErrors(Buffer const & buf, TeXErrors const & terr,
275                                   ErrorList & errorList)
276 {
277         TeXErrors::Errors::const_iterator cit = terr.begin();
278         TeXErrors::Errors::const_iterator end = terr.end();
279
280         for (; cit != end; ++cit) {
281                 int id_start = -1;
282                 int pos_start = -1;
283                 int errorrow = cit->error_in_line;
284                 bool found = buf.texrow().getIdFromRow(errorrow, id_start,
285                                                        pos_start);
286                 int id_end = -1;
287                 int pos_end = -1;
288                 do {
289                         ++errorrow;
290                         found = buf.texrow().getIdFromRow(errorrow, id_end,
291                                                           pos_end);
292                 } while (found && id_start == id_end && pos_start == pos_end);
293
294                 errorList.push_back(ErrorItem(cit->error_desc,
295                         cit->error_text, id_start, pos_start, pos_end));
296         }
297 }
298
299
300 string const bufferFormat(Buffer const & buffer)
301 {
302         if (buffer.isDocBook())
303                 return "docbook";
304         else if (buffer.isLiterate())
305                 return "literate";
306         else
307                 return "latex";
308 }
309
310
311 int countWords(DocIterator const & from, DocIterator const & to)
312 {
313         int count = 0;
314         bool inword = false;
315         for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
316                 // Copied and adapted from isLetter() in ControlSpellChecker
317                 if (dit.inTexted()
318                     && dit.pos() != dit.lastpos()
319                     && dit.paragraph().isLetter(dit.pos())
320                     && !dit.paragraph().isDeleted(dit.pos())) {
321                         if (!inword) {
322                                 ++count;
323                                 inword = true;
324                         }
325                 } else if (inword)
326                         inword = false;
327         }
328
329         return count;
330 }
331
332
333 namespace {
334
335 depth_type getDepth(DocIterator const & it)
336 {
337         depth_type depth = 0;
338         for (size_t i = 0 ; i < it.depth() ; ++i)
339                 if (!it[i].inset().inMathed())
340                         depth += it[i].paragraph().getDepth() + 1;
341         // remove 1 since the outer inset does not count
342         return depth - 1;
343 }
344
345 depth_type getItemDepth(ParIterator const & it)
346 {
347         Paragraph const & par = *it;
348         LYX_LABEL_TYPES const labeltype = par.layout()->labeltype;
349
350         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
351                 return 0;
352
353         // this will hold the lowest depth encountered up to now.
354         depth_type min_depth = getDepth(it);
355         ParIterator prev_it = it;
356         while (true) {
357                 if (prev_it.pit())
358                         --prev_it.top().pit();
359                 else {
360                         // start of nested inset: go to outer par
361                         prev_it.pop_back();
362                         if (prev_it.empty()) {
363                                 // start of document: nothing to do
364                                 return 0;
365                         }
366                 }
367
368                 // We search for the first paragraph with same label
369                 // that is not more deeply nested.
370                 Paragraph & prev_par = *prev_it;
371                 depth_type const prev_depth = getDepth(prev_it);
372                 if (labeltype == prev_par.layout()->labeltype) {
373                         if (prev_depth < min_depth) {
374                                 return prev_par.itemdepth + 1;
375                         }
376                         else if (prev_depth == min_depth) {
377                                 return prev_par.itemdepth;
378                         }
379                 }
380                 min_depth = std::min(min_depth, prev_depth);
381                 // small optimization: if we are at depth 0, we won't
382                 // find anything else
383                 if (prev_depth == 0) {
384                         return 0;
385                 }
386         }
387 }
388
389
390 bool needEnumCounterReset(ParIterator const & it)
391 {
392         Paragraph const & par = *it;
393         BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
394         depth_type const cur_depth = par.getDepth();
395         ParIterator prev_it = it;
396         while (prev_it.pit()) {
397                 --prev_it.top().pit();
398                 Paragraph const & prev_par = *prev_it;
399                 if (prev_par.getDepth() <= cur_depth)
400                         return  prev_par.layout()->labeltype != LABEL_ENUMERATE;
401         }
402         // start of nested inset: reset
403         return true;
404 }
405
406
407 // set the label of a paragraph. This includes the counters.
408 void setLabel(Buffer const & buf, ParIterator & it)
409 {
410         TextClass const & textclass = buf.params().getTextClass();
411         Paragraph & par = it.paragraph();
412         Layout_ptr const & layout = par.layout();
413         Counters & counters = textclass.counters();
414
415         if (par.params().startOfAppendix()) {
416                 // FIXME: only the counter corresponding to toplevel
417                 // sectionning should be reset
418                 counters.reset();
419                 counters.appendix(true);
420         }
421         par.params().appendix(counters.appendix());
422
423         // Compute the item depth of the paragraph
424         par.itemdepth = getItemDepth(it);
425
426         if (layout->margintype == MARGIN_MANUAL) {
427                 if (par.params().labelWidthString().empty())
428                         par.params().labelWidthString(par.translateIfPossible(layout->labelstring(), buf.params()));
429         } else {
430                 par.params().labelWidthString(docstring());
431         }
432
433         switch(layout->labeltype) {
434         case LABEL_COUNTER:
435                 if (layout->toclevel <= buf.params().secnumdepth
436                     && (layout->latextype != LATEX_ENVIRONMENT
437                         || isFirstInSequence(it.pit(), it.plist()))) {
438                         counters.step(layout->counter);
439                         par.params().labelString(
440                                 par.expandLabel(layout, buf.params()));
441                 } else
442                         par.params().labelString(docstring());
443                 break;
444
445         case LABEL_ITEMIZE: {
446                 // At some point of time we should do something more
447                 // clever here, like:
448                 //   par.params().labelString(
449                 //    buf.params().user_defined_bullet(par.itemdepth).getText());
450                 // for now, use a simple hardcoded label
451                 docstring itemlabel;
452                 switch (par.itemdepth) {
453                 case 0:
454                         itemlabel = char_type(0x2022);
455                         break;
456                 case 1:
457                         itemlabel = char_type(0x2013);
458                         break;
459                 case 2:
460                         itemlabel = char_type(0x2217);
461                         break;
462                 case 3:
463                         itemlabel = char_type(0x2219); // or 0x00b7
464                         break;
465                 }
466                 par.params().labelString(itemlabel);
467                 break;
468         }
469
470         case LABEL_ENUMERATE: {
471                 // FIXME: Yes I know this is a really, really! bad solution
472                 // (Lgb)
473                 docstring enumcounter = from_ascii("enum");
474
475                 switch (par.itemdepth) {
476                 case 2:
477                         enumcounter += 'i';
478                 case 1:
479                         enumcounter += 'i';
480                 case 0:
481                         enumcounter += 'i';
482                         break;
483                 case 3:
484                         enumcounter += "iv";
485                         break;
486                 default:
487                         // not a valid enumdepth...
488                         break;
489                 }
490
491                 // Maybe we have to reset the enumeration counter.
492                 if (needEnumCounterReset(it))
493                         counters.reset(enumcounter);
494
495                 counters.step(enumcounter);
496
497                 string format;
498
499                 switch (par.itemdepth) {
500                 case 0:
501                         format = N_("\\arabic{enumi}.");
502                         break;
503                 case 1:
504                         format = N_("(\\alph{enumii})");
505                         break;
506                 case 2:
507                         format = N_("\\roman{enumiii}.");
508                         break;
509                 case 3:
510                         format = N_("\\Alph{enumiv}.");
511                         break;
512                 default:
513                         // not a valid enumdepth...
514                         break;
515                 }
516
517                 par.params().labelString(counters.counterLabel(
518                         par.translateIfPossible(from_ascii(format), buf.params())));
519
520                 break;
521         }
522
523         case LABEL_SENSITIVE: {
524                 string const & type = counters.current_float();
525                 docstring full_label;
526                 if (type.empty())
527                         full_label = buf.B_("Senseless!!! ");
528                 else {
529                         docstring name = buf.B_(textclass.floats().getType(type).name());
530                         if (counters.hasCounter(from_utf8(type))) {
531                                 counters.step(from_utf8(type));
532                                 full_label = bformat(from_ascii("%1$s %2$s:"), 
533                                                      name, 
534                                                      counters.theCounter(from_utf8(type)));
535                         } else
536                                 full_label = bformat(from_ascii("%1$s #:"), name);      
537                 }
538                 par.params().labelString(full_label);   
539                 break;
540         }
541
542         case LABEL_NO_LABEL:
543                 par.params().labelString(docstring());
544                 break;
545
546         case LABEL_MANUAL:
547         case LABEL_TOP_ENVIRONMENT:
548         case LABEL_CENTERED_TOP_ENVIRONMENT:
549         case LABEL_STATIC:      
550         case LABEL_BIBLIO:
551                 par.params().labelString(
552                         par.translateIfPossible(layout->labelstring(), 
553                                                 buf.params()));
554                 break;
555         }
556 }
557
558 } // anon namespace
559
560 void updateLabels(Buffer const & buf, ParIterator & parit)
561 {
562         BOOST_ASSERT(parit.pit() == 0);
563
564         depth_type maxdepth = 0;
565         pit_type const lastpit = parit.lastpit();
566         for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
567                 // reduce depth if necessary
568                 parit->params().depth(min(parit->params().depth(), maxdepth));
569                 maxdepth = parit->getMaxDepthAfter();
570
571                 // set the counter for this paragraph
572                 setLabel(buf, parit);
573
574                 // Now the insets
575                 InsetList::const_iterator iit = parit->insetlist.begin();
576                 InsetList::const_iterator end = parit->insetlist.end();
577                 for (; iit != end; ++iit) {
578                         parit.pos() = iit->pos;
579                         iit->inset->updateLabels(buf, parit);
580                 }
581         }
582         
583 }
584
585
586 // FIXME: buf should should be const because updateLabels() modifies
587 // the contents of the paragraphs.
588 void updateLabels(Buffer const & buf, bool childonly)
589 {
590         Buffer const * const master = buf.getMasterBuffer();
591         // Use the master text class also for child documents
592         TextClass const & textclass = master->params().getTextClass();
593
594         if (!childonly) {
595                 // If this is a child document start with the master
596                 if (master != &buf) {
597                         updateLabels(*master);
598                         return;
599                 }
600
601                 // start over the counters
602                 textclass.counters().reset();
603         }
604
605         Buffer & cbuf = const_cast<Buffer &>(buf);
606
607         if (buf.text().empty()) {
608                 // FIXME: we don't call continue with updateLabels()
609                 // here because it crashes on newly created documents.
610                 // But the TocBackend needs to be initialised
611                 // nonetheless so we update the tocBackend manually.
612                 cbuf.tocBackend().update();
613                 return;
614         }
615
616         // do the real work
617         ParIterator parit = par_iterator_begin(buf.inset());
618         updateLabels(buf, parit);
619
620         cbuf.tocBackend().update();
621         if (!childonly)
622                 cbuf.structureChanged();
623 }
624
625
626 void checkBufferStructure(Buffer & buffer, ParIterator const & par_it)
627 {
628         if (par_it->layout()->toclevel != Layout::NOT_IN_TOC) {
629                 Buffer * master = buffer.getMasterBuffer();
630                 master->tocBackend().updateItem(par_it);
631                 master->structureChanged();
632         }
633 }
634
635
636 void loadChildDocuments(Buffer const & buf)
637 {
638         bool parse_error = false;
639                 
640         for (InsetIterator it = inset_iterator_begin(buf.inset()); it; ++it) {
641                 if (it->lyxCode() != Inset::INCLUDE_CODE)
642                         continue;
643                 InsetInclude const & inset = static_cast<InsetInclude const &>(*it);
644                 InsetCommandParams const & ip = inset.params();
645                 Buffer * child = loadIfNeeded(buf, ip);
646                 if (!child)
647                         continue;
648                 parse_error |= !child->errorList("Parse").empty();
649                 loadChildDocuments(*child);
650         }
651
652         if (use_gui && buf.getMasterBuffer() == &buf)
653                 updateLabels(buf);
654 }
655
656 } // namespace lyx