]> git.lyx.org Git - features.git/blob - src/buffer.C
Introducing a number of tags parametrizing various
[features.git] / src / buffer.C
1 /**
2  * \file buffer.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  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "buffer.h"
14
15 #include "author.h"
16 #include "buffer_funcs.h"
17 #include "bufferlist.h"
18 #include "bufferparams.h"
19 #include "counters.h"
20 #include "Bullet.h"
21 #include "Chktex.h"
22 #include "debug.h"
23 #include "errorlist.h"
24 #include "exporter.h"
25 #include "format.h"
26 #include "funcrequest.h"
27 #include "gettext.h"
28 #include "iterators.h"
29 #include "language.h"
30 #include "LaTeX.h"
31 #include "LaTeXFeatures.h"
32 #include "LyXAction.h"
33 #include "lyxlex.h"
34 #include "lyxrc.h"
35 #include "lyxvc.h"
36 #include "messages.h"
37 #include "output.h"
38 #include "output_docbook.h"
39 #include "output_latex.h"
40 #include "output_linuxdoc.h"
41 #include "paragraph.h"
42 #include "paragraph_funcs.h"
43 #include "ParagraphParameters.h"
44 #include "PosIterator.h"
45 #include "sgml.h"
46 #include "texrow.h"
47 #include "undo.h"
48 #include "version.h"
49
50 #include "insets/insetbibitem.h"
51 #include "insets/insetbibtex.h"
52 #include "insets/insetinclude.h"
53 #include "insets/insettext.h"
54
55 #include "frontends/Alert.h"
56
57 #include "graphics/Previews.h"
58
59 #include "support/FileInfo.h"
60 #include "support/filetools.h"
61 #include "support/gzstream.h"
62 #include "support/lyxlib.h"
63 #include "support/os.h"
64 #include "support/path.h"
65 #include "support/textutils.h"
66 #include "support/tostr.h"
67
68 #include <boost/bind.hpp>
69
70 #include "support/std_sstream.h"
71
72 #include <iomanip>
73 #include <stack>
74
75 #include <utime.h>
76
77 #ifdef HAVE_LOCALE
78 #endif
79
80 using lyx::pos_type;
81
82 using lyx::support::AddName;
83 using lyx::support::atoi;
84 using lyx::support::bformat;
85 using lyx::support::ChangeExtension;
86 using lyx::support::cmd_ret;
87 using lyx::support::CreateBufferTmpDir;
88 using lyx::support::destroyDir;
89 using lyx::support::FileInfo;
90 using lyx::support::FileInfo;
91 using lyx::support::getExtFromContents;
92 using lyx::support::IsDirWriteable;
93 using lyx::support::IsFileWriteable;
94 using lyx::support::LibFileSearch;
95 using lyx::support::ltrim;
96 using lyx::support::MakeAbsPath;
97 using lyx::support::MakeDisplayPath;
98 using lyx::support::MakeLatexName;
99 using lyx::support::OnlyFilename;
100 using lyx::support::OnlyPath;
101 using lyx::support::Path;
102 using lyx::support::QuoteName;
103 using lyx::support::removeAutosaveFile;
104 using lyx::support::rename;
105 using lyx::support::RunCommand;
106 using lyx::support::split;
107 using lyx::support::strToInt;
108 using lyx::support::subst;
109 using lyx::support::tempName;
110 using lyx::support::trim;
111
112 namespace os = lyx::support::os;
113
114 using std::endl;
115 using std::for_each;
116 using std::make_pair;
117
118 using std::ifstream;
119 using std::ios;
120 using std::ostream;
121 using std::ostringstream;
122 using std::ofstream;
123 using std::pair;
124 using std::stack;
125 using std::vector;
126 using std::string;
127
128
129 // all these externs should eventually be removed.
130 extern BufferList bufferlist;
131
132 namespace {
133
134 const int LYX_FORMAT = 225;
135
136 } // namespace anon
137
138
139 typedef std::map<string, bool> DepClean;
140
141 struct Buffer::Impl
142 {
143         Impl(Buffer & parent, string const & file, bool readonly);
144
145         limited_stack<Undo> undostack;
146         limited_stack<Undo> redostack;
147         BufferParams params;
148         ParagraphList paragraphs;
149         LyXVC lyxvc;
150         string temppath;
151         bool nicefile;
152         TexRow texrow;
153
154         /// need to regenerate .tex ?
155         DepClean dep_clean;
156
157         /// is save needed
158         mutable bool lyx_clean;
159
160         /// is autosave needed
161         mutable bool bak_clean;
162
163         /// is this a unnamed file (New...)
164         bool unnamed;
165
166         /// buffer is r/o
167         bool read_only;
168
169         /// name of the file the buffer is associated with.
170         string filename;
171
172         /// The path to the document file.
173         string filepath;
174
175         boost::scoped_ptr<Messages> messages;
176
177         /** set to true only when the file is fully loaded.
178          *  Used to prevent the premature generation of previews
179          *  and by the citation inset.
180          */
181         bool file_fully_loaded;
182 };
183
184
185 Buffer::Impl::Impl(Buffer & parent, string const & file, bool readonly_)
186         : nicefile(true),
187           lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
188           filename(file), filepath(OnlyPath(file)), file_fully_loaded(false)
189 {
190         lyxvc.buffer(&parent);
191         if (readonly_ || lyxrc.use_tempdir)
192                 temppath = CreateBufferTmpDir();
193 }
194
195
196 Buffer::Buffer(string const & file, bool ronly)
197         : pimpl_(new Impl(*this, file, ronly))
198 {
199         lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
200 }
201
202
203 Buffer::~Buffer()
204 {
205         lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
206         // here the buffer should take care that it is
207         // saved properly, before it goes into the void.
208
209         closing();
210
211         if (!temppath().empty() && destroyDir(temppath()) != 0) {
212                 Alert::warning(_("Could not remove temporary directory"),
213                         bformat(_("Could not remove the temporary directory %1$s"), temppath()));
214         }
215
216         paragraphs().clear();
217
218         // Remove any previewed LaTeX snippets associated with this buffer.
219         lyx::graphics::Previews::get().removeLoader(*this);
220 }
221
222
223 limited_stack<Undo> & Buffer::undostack()
224 {
225         return pimpl_->undostack;
226 }
227
228
229 limited_stack<Undo> const & Buffer::undostack() const
230 {
231         return pimpl_->undostack;
232 }
233
234
235 limited_stack<Undo> & Buffer::redostack()
236 {
237         return pimpl_->redostack;
238 }
239
240
241 limited_stack<Undo> const & Buffer::redostack() const
242 {
243         return pimpl_->redostack;
244 }
245
246
247 BufferParams & Buffer::params()
248 {
249         return pimpl_->params;
250 }
251
252
253 BufferParams const & Buffer::params() const
254 {
255         return pimpl_->params;
256 }
257
258
259 ParagraphList & Buffer::paragraphs()
260 {
261         return pimpl_->paragraphs;
262 }
263
264
265 ParagraphList const & Buffer::paragraphs() const
266 {
267         return pimpl_->paragraphs;
268 }
269
270
271 LyXVC & Buffer::lyxvc()
272 {
273         return pimpl_->lyxvc;
274 }
275
276
277 LyXVC const & Buffer::lyxvc() const
278 {
279         return pimpl_->lyxvc;
280 }
281
282
283 string const & Buffer::temppath() const
284 {
285         return pimpl_->temppath;
286 }
287
288
289 bool & Buffer::niceFile()
290 {
291         return pimpl_->nicefile;
292 }
293
294
295 bool Buffer::niceFile() const
296 {
297         return pimpl_->nicefile;
298 }
299
300
301 TexRow & Buffer::texrow()
302 {
303         return pimpl_->texrow;
304 }
305
306
307 TexRow const & Buffer::texrow() const
308 {
309         return pimpl_->texrow;
310 }
311
312
313 string const Buffer::getLatexName(bool no_path) const
314 {
315         string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
316         return no_path ? OnlyFilename(name) : name;
317 }
318
319
320 pair<Buffer::LogType, string> const Buffer::getLogName() const
321 {
322         string const filename = getLatexName(false);
323
324         if (filename.empty())
325                 return make_pair(Buffer::latexlog, string());
326
327         string path = OnlyPath(filename);
328
329         if (lyxrc.use_tempdir || !IsDirWriteable(path))
330                 path = temppath();
331
332         string const fname = AddName(path,
333                                      OnlyFilename(ChangeExtension(filename,
334                                                                   ".log")));
335         string const bname =
336                 AddName(path, OnlyFilename(
337                         ChangeExtension(filename,
338                                         formats.extension("literate") + ".out")));
339
340         // If no Latex log or Build log is newer, show Build log
341
342         FileInfo const f_fi(fname);
343         FileInfo const b_fi(bname);
344
345         if (b_fi.exist() &&
346             (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
347                 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
348                 return make_pair(Buffer::buildlog, bname);
349         }
350         lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
351         return make_pair(Buffer::latexlog, fname);
352 }
353
354
355 void Buffer::setReadonly(bool flag)
356 {
357         if (pimpl_->read_only != flag) {
358                 pimpl_->read_only = flag;
359                 readonly(flag);
360         }
361 }
362
363
364 void Buffer::setFileName(string const & newfile)
365 {
366         pimpl_->filename = MakeAbsPath(newfile);
367         pimpl_->filepath = OnlyPath(pimpl_->filename);
368         setReadonly(IsFileWriteable(pimpl_->filename) == 0);
369         updateTitles();
370 }
371
372
373 // We'll remove this later. (Lgb)
374 namespace {
375
376 void unknownClass(string const & unknown)
377 {
378         Alert::warning(_("Unknown document class"),
379                 bformat(_("Using the default document class, because the "
380                         "class %1$s is unknown."), unknown));
381 }
382
383 } // anon
384
385 int Buffer::readHeader(LyXLex & lex)
386 {
387         int unknown_tokens = 0;
388
389         while (lex.isOK()) {
390                 lex.nextToken();
391                 string const token = lex.getString();
392
393                 if (token.empty())
394                         continue;
395
396                 if (token == "\\end_header")
397                         break;
398
399                 lyxerr[Debug::PARSER] << "Handling header token: `"
400                                       << token << '\'' << endl;
401
402
403                 string unknown = params().readToken(lex, token);
404                 if (!unknown.empty()) {
405                         if (unknown[0] != '\\') {
406                                 unknownClass(unknown);
407                         } else {
408                                 ++unknown_tokens;
409                                 string const s = bformat(_("Unknown token: "
410                                                            "%1$s %2$s\n"),
411                                                          token,
412                                                          lex.getString());
413                                 error(ErrorItem(_("Header error"), s,
414                                                 -1, 0, 0));
415                         }
416                 }
417         }
418         return unknown_tokens;
419 }
420
421
422 // candidate for move to BufferView
423 // (at least some parts in the beginning of the func)
424 //
425 // Uwe C. Schroeder
426 // changed to be public and have one parameter
427 // if par = 0 normal behavior
428 // else insert behavior
429 // Returns false if "\end_document" is not read (Asger)
430 bool Buffer::readBody(LyXLex & lex, ParagraphList::iterator pit)
431 {
432         Paragraph::depth_type depth = 0;
433         bool the_end_read = false;
434
435         if (paragraphs().empty()) {
436                 readHeader(lex);
437                 if (!params().getLyXTextClass().load()) {
438                         string theclass = params().getLyXTextClass().name();
439                         Alert::error(_("Can't load document class"), bformat(
440                                         "Using the default document class, because the "
441                                         " class %1$s could not be loaded.", theclass));
442                         params().textclass = 0;
443                 }
444         } else {
445                 // We don't want to adopt the parameters from the
446                 // document we insert, so read them into a temporary buffer
447                 // and then discard it
448
449                 Buffer tmpbuf("", false);
450                 tmpbuf.readHeader(lex);
451         }
452
453         while (lex.isOK()) {
454                 lex.nextToken();
455                 string const token = lex.getString();
456
457                 if (token.empty())
458                         continue;
459
460                 lyxerr[Debug::PARSER] << "Handling token: `"
461                                       << token << '\'' << endl;
462
463                 if (token == "\\end_document") {
464                         the_end_read = true;
465                         continue;
466                 }
467
468                 readParagraph(lex, token, paragraphs(), pit, depth);
469         }
470
471         return the_end_read;
472 }
473
474
475 int Buffer::readParagraph(LyXLex & lex, string const & token,
476                           ParagraphList & pars, ParagraphList::iterator & pit,
477                           lyx::depth_type & depth)
478 {
479         static Change current_change;
480         int unknown = 0;
481
482         if (token == "\\begin_layout") {
483                 lex.pushToken(token);
484
485                 Paragraph par;
486                 par.params().depth(depth);
487                 if (params().tracking_changes)
488                         par.trackChanges();
489                 LyXFont f(LyXFont::ALL_INHERIT, params().language);
490                 par.setFont(0, f);
491
492                 // insert after
493                 if (pit != pars.end())
494                         ++pit;
495
496                 pit = pars.insert(pit, par);
497
498                 // FIXME: goddamn InsetTabular makes us pass a Buffer
499                 // not BufferParams
500                 ::readParagraph(*this, *pit, lex);
501
502         } else if (token == "\\begin_deeper") {
503                 ++depth;
504         } else if (token == "\\end_deeper") {
505                 if (!depth) {
506                         lex.printError("\\end_deeper: " "depth is already null");
507                 } else {
508                         --depth;
509                 }
510         } else {
511                 ++unknown;
512         }
513         return unknown;
514 }
515
516
517 // needed to insert the selection
518 void Buffer::insertStringAsLines(ParagraphList::iterator & par, pos_type & pos,
519                                  LyXFont const & fn,string const & str)
520 {
521         LyXLayout_ptr const & layout = par->layout();
522
523         LyXFont font = fn;
524
525         par->checkInsertChar(font);
526         // insert the string, don't insert doublespace
527         bool space_inserted = true;
528         bool autobreakrows = !par->inInset() ||
529                 static_cast<InsetText *>(par->inInset())->getAutoBreakRows();
530         for(string::const_iterator cit = str.begin();
531             cit != str.end(); ++cit) {
532                 if (*cit == '\n') {
533                         if (autobreakrows && (!par->empty() || par->allowEmpty())) {
534                                 breakParagraph(params(), paragraphs(), par, pos,
535                                                layout->isEnvironment());
536                                 ++par;
537                                 pos = 0;
538                                 space_inserted = true;
539                         } else {
540                                 continue;
541                         }
542                         // do not insert consecutive spaces if !free_spacing
543                 } else if ((*cit == ' ' || *cit == '\t') &&
544                            space_inserted && !par->isFreeSpacing()) {
545                         continue;
546                 } else if (*cit == '\t') {
547                         if (!par->isFreeSpacing()) {
548                                 // tabs are like spaces here
549                                 par->insertChar(pos, ' ', font);
550                                 ++pos;
551                                 space_inserted = true;
552                         } else {
553                                 const pos_type nb = 8 - pos % 8;
554                                 for (pos_type a = 0; a < nb ; ++a) {
555                                         par->insertChar(pos, ' ', font);
556                                         ++pos;
557                                 }
558                                 space_inserted = true;
559                         }
560                 } else if (!IsPrintable(*cit)) {
561                         // Ignore unprintables
562                         continue;
563                 } else {
564                         // just insert the character
565                         par->insertChar(pos, *cit, font);
566                         ++pos;
567                         space_inserted = (*cit == ' ');
568                 }
569
570         }
571 }
572
573
574 bool Buffer::readFile(string const & filename)
575 {
576         // Check if the file is compressed.
577         string const format = getExtFromContents(filename);
578         if (format == "gzip" || format == "zip" || format == "compress") {
579                 params().compressed = true;
580         }
581
582         bool ret = readFile(filename, paragraphs().begin());
583
584         // After we have read a file, we must ensure that the buffer
585         // language is set and used in the gui.
586         // If you know of a better place to put this, please tell me. (Lgb)
587         updateDocLang(params().language);
588
589         return ret;
590 }
591
592
593 bool Buffer::readFile(string const & filename, ParagraphList::iterator pit)
594 {
595         LyXLex lex(0, 0);
596         lex.setFile(filename);
597
598         return readFile(lex, filename, pit);
599 }
600
601
602 bool Buffer::fully_loaded() const
603 {
604         return pimpl_->file_fully_loaded;
605 }
606
607
608 void Buffer::fully_loaded(bool value)
609 {
610         pimpl_->file_fully_loaded = value;
611 }
612
613
614 bool Buffer::readFile(LyXLex & lex, string const & filename,
615                       ParagraphList::iterator pit)
616 {
617         BOOST_ASSERT(!filename.empty());
618
619         if (!lex.isOK()) {
620                 Alert::error(_("Document could not be read"),
621                              bformat(_("%1$s could not be read."), filename));
622                 return false;
623         }
624
625         lex.next();
626         string const token(lex.getString());
627
628         if (!lex.isOK()) {
629                 Alert::error(_("Document could not be read"),
630                              bformat(_("%1$s could not be read."), filename));
631                 return false;
632         }
633
634         // the first token _must_ be...
635         if (token != "\\lyxformat") {
636                 lyxerr << "Token: " << token << endl;
637
638                 Alert::error(_("Document format failure"),
639                              bformat(_("%1$s is not a LyX document."),
640                                        filename));
641                 return false;
642         }
643
644         lex.eatLine();
645         string tmp_format = lex.getString();
646         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
647         // if present remove ".," from string.
648         string::size_type dot = tmp_format.find_first_of(".,");
649         //lyxerr << "           dot found at " << dot << endl;
650         if (dot != string::npos)
651                         tmp_format.erase(dot, 1);
652         int file_format = strToInt(tmp_format);
653         //lyxerr << "format: " << file_format << endl;
654
655         if (file_format > LYX_FORMAT) {
656                 Alert::warning(_("Document format failure"),
657                                bformat(_("%1$s was created with a newer"
658                                          " version of LyX. This is likely to"
659                                          " cause problems."),
660                                          filename));
661         } else if (file_format < LYX_FORMAT) {
662                 string const tmpfile = tempName();
663                 string command = LibFileSearch("lyx2lyx", "lyx2lyx");
664                 if (command.empty()) {
665                         Alert::error(_("Conversion script not found"),
666                                      bformat(_("%1$s is from an earlier"
667                                                " version of LyX, but the"
668                                                " conversion script lyx2lyx"
669                                                " could not be found."),
670                                                filename));
671                         return false;
672                 }
673                 command += " -t"
674                         + tostr(LYX_FORMAT)
675                         + " -o " + tmpfile + ' '
676                         + QuoteName(filename);
677                 lyxerr[Debug::INFO] << "Running '"
678                                     << command << '\''
679                                     << endl;
680                 cmd_ret const ret = RunCommand(command);
681                 if (ret.first != 0) {
682                         Alert::error(_("Conversion script failed"),
683                                      bformat(_("%1$s is from an earlier version"
684                                               " of LyX, but the lyx2lyx script"
685                                               " failed to convert it."),
686                                               filename));
687                         return false;
688                 } else {
689                         bool ret = readFile(tmpfile, pit);
690                         // Do stuff with tmpfile name and buffer name here.
691                         return ret;
692                 }
693
694         }
695
696         bool the_end = readBody(lex, pit);
697         params().setPaperStuff();
698
699         if (!the_end) {
700                 Alert::error(_("Document format failure"),
701                              bformat(_("%1$s ended unexpectedly, which means"
702                                        " that it is probably corrupted."),
703                                        filename));
704         }
705         pimpl_->file_fully_loaded = true;
706         return true;
707 }
708
709
710 // Should probably be moved to somewhere else: BufferView? LyXView?
711 bool Buffer::save() const
712 {
713         // We don't need autosaves in the immediate future. (Asger)
714         resetAutosaveTimers();
715
716         // make a backup
717         string s;
718         if (lyxrc.make_backup) {
719                 s = fileName() + '~';
720                 if (!lyxrc.backupdir_path.empty())
721                         s = AddName(lyxrc.backupdir_path,
722                                     subst(os::slashify_path(s),'/','!'));
723
724                 // Rename is the wrong way of making a backup,
725                 // this is the correct way.
726                 /* truss cp fil fil2:
727                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
728                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
729                    open("LyXVC.lyx", O_RDONLY)                     = 3
730                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
731                    fstat(4, 0xEFFFF508)                            = 0
732                    fstat(3, 0xEFFFF508)                            = 0
733                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
734                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
735                    read(3, 0xEFFFD4A0, 8192)                       = 0
736                    close(4)                                        = 0
737                    close(3)                                        = 0
738                    chmod("LyXVC3.lyx", 0100644)                    = 0
739                    lseek(0, 0, SEEK_CUR)                           = 46440
740                    _exit(0)
741                 */
742
743                 // Should probably have some more error checking here.
744                 // Doing it this way, also makes the inodes stay the same.
745                 // This is still not a very good solution, in particular we
746                 // might loose the owner of the backup.
747                 FileInfo finfo(fileName());
748                 if (finfo.exist()) {
749                         mode_t fmode = finfo.getMode();
750                         struct utimbuf times = {
751                                 finfo.getAccessTime(),
752                                 finfo.getModificationTime() };
753
754                         ifstream ifs(fileName().c_str());
755                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
756                         if (ifs && ofs) {
757                                 ofs << ifs.rdbuf();
758                                 ifs.close();
759                                 ofs.close();
760                                 ::chmod(s.c_str(), fmode);
761
762                                 if (::utime(s.c_str(), &times)) {
763                                         lyxerr << "utime error." << endl;
764                                 }
765                         } else {
766                                 lyxerr << "LyX was not able to make "
767                                         "backup copy. Beware." << endl;
768                         }
769                 }
770         }
771
772         if (writeFile(fileName())) {
773                 markClean();
774                 removeAutosaveFile(fileName());
775         } else {
776                 // Saving failed, so backup is not backup
777                 if (lyxrc.make_backup) {
778                         rename(s, fileName());
779                 }
780                 return false;
781         }
782         return true;
783 }
784
785
786 bool Buffer::writeFile(string const & fname) const
787 {
788         if (pimpl_->read_only && (fname == fileName())) {
789                 return false;
790         }
791
792         FileInfo finfo(fname);
793         if (finfo.exist() && !finfo.writable()) {
794                 return false;
795         }
796
797         bool retval;
798
799         if (params().compressed) {
800                 gz::ogzstream ofs(fname.c_str());
801
802                 if (!ofs)
803                         return false;
804
805                 retval = do_writeFile(ofs);
806
807         } else {
808                 ofstream ofs(fname.c_str());
809                 if (!ofs)
810                         return false;
811
812                 retval = do_writeFile(ofs);
813         }
814
815         return retval;
816 }
817
818
819 bool Buffer::do_writeFile(ostream & ofs) const
820 {
821
822 #ifdef HAVE_LOCALE
823         // Use the standard "C" locale for file output.
824         ofs.imbue(std::locale::classic());
825 #endif
826
827         // The top of the file should not be written by params().
828
829         // write out a comment in the top of the file
830         ofs << "#LyX " << lyx_version
831             << " created this file. For more info see http://www.lyx.org/\n"
832             << "\\lyxformat " << LYX_FORMAT << "\n";
833
834         // now write out the buffer paramters.
835         params().writeFile(ofs);
836
837         ofs << "\\end_header\n";
838
839         Paragraph::depth_type depth = 0;
840
841         // this will write out all the paragraphs
842         // using recursive descent.
843         ParagraphList::const_iterator pit = paragraphs().begin();
844         ParagraphList::const_iterator pend = paragraphs().end();
845         for (; pit != pend; ++pit)
846                 pit->write(*this, ofs, params(), depth);
847
848         // Write marker that shows file is complete
849         ofs << "\n\\end_document" << endl;
850
851         // Shouldn't really be needed....
852         //ofs.close();
853
854         // how to check if close went ok?
855         // Following is an attempt... (BE 20001011)
856
857         // good() returns false if any error occured, including some
858         //        formatting error.
859         // bad()  returns true if something bad happened in the buffer,
860         //        which should include file system full errors.
861
862         bool status = true;
863         if (!ofs.good()) {
864                 status = false;
865 #if 0
866                 if (ofs.bad()) {
867                         lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
868                 } else {
869                         lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
870                                << endl;
871                 }
872 #endif
873         }
874
875         return status;
876 }
877
878
879 void Buffer::makeLaTeXFile(string const & fname,
880                            string const & original_path,
881                            OutputParams const & runparams,
882                            bool output_preamble, bool output_body)
883 {
884         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
885
886         ofstream ofs;
887         if (!openFileWrite(ofs, fname))
888                 return;
889
890         makeLaTeXFile(ofs, original_path,
891                       runparams, output_preamble, output_body);
892
893         ofs.close();
894         if (ofs.fail()) {
895                 lyxerr << "File was not closed properly." << endl;
896         }
897 }
898
899
900 void Buffer::makeLaTeXFile(ostream & os,
901                            string const & original_path,
902                            OutputParams const & runparams_in,
903                            bool output_preamble, bool output_body)
904 {
905         OutputParams runparams = runparams_in;
906         niceFile() = runparams.nice; // this will be used by Insetincludes.
907
908         // validate the buffer.
909         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
910         LaTeXFeatures features(*this, params());
911         validate(features);
912         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
913
914         texrow().reset();
915         // The starting paragraph of the coming rows is the
916         // first paragraph of the document. (Asger)
917         texrow().start(paragraphs().begin()->id(), 0);
918
919         if (output_preamble && runparams.nice) {
920                 os << "%% LyX " << lyx_version << " created this file.  "
921                         "For more info, see http://www.lyx.org/.\n"
922                         "%% Do not edit unless you really know what "
923                         "you are doing.\n";
924                 texrow().newline();
925                 texrow().newline();
926         }
927         lyxerr[Debug::INFO] << "lyx header finished" << endl;
928         // There are a few differences between nice LaTeX and usual files:
929         // usual is \batchmode and has a
930         // special input@path to allow the including of figures
931         // with either \input or \includegraphics (what figinsets do).
932         // input@path is set when the actual parameter
933         // original_path is set. This is done for usual tex-file, but not
934         // for nice-latex-file. (Matthias 250696)
935         if (output_preamble) {
936                 if (!runparams.nice) {
937                         // code for usual, NOT nice-latex-file
938                         os << "\\batchmode\n"; // changed
939                         // from \nonstopmode
940                         texrow().newline();
941                 }
942                 if (!original_path.empty()) {
943                         string inputpath = os::external_path(original_path);
944                         subst(inputpath, "~", "\\string~");
945                         os << "\\makeatletter\n"
946                             << "\\def\\input@path{{"
947                             << inputpath << "/}}\n"
948                             << "\\makeatother\n";
949                         texrow().newline();
950                         texrow().newline();
951                         texrow().newline();
952                 }
953
954                 // Write the preamble
955                 runparams.use_babel = params().writeLaTeX(os, features, texrow());
956
957                 if (!output_body)
958                         return;
959
960                 // make the body.
961                 os << "\\begin{document}\n";
962                 texrow().newline();
963         } // output_preamble
964         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
965
966         if (!lyxrc.language_auto_begin) {
967                 os << subst(lyxrc.language_command_begin, "$$lang",
968                              params().language->babel())
969                     << endl;
970                 texrow().newline();
971         }
972
973         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
974
975         // add this just in case after all the paragraphs
976         os << endl;
977         texrow().newline();
978
979         if (!lyxrc.language_auto_end) {
980                 os << subst(lyxrc.language_command_end, "$$lang",
981                              params().language->babel())
982                     << endl;
983                 texrow().newline();
984         }
985
986         if (output_preamble) {
987                 os << "\\end{document}\n";
988                 texrow().newline();
989
990                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
991         } else {
992                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
993                                      << endl;
994         }
995
996         // Just to be sure. (Asger)
997         texrow().newline();
998
999         lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
1000         lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
1001                             << '.' << endl;
1002
1003         // we want this to be true outside previews (for insetexternal)
1004         niceFile() = true;
1005 }
1006
1007
1008 bool Buffer::isLatex() const
1009 {
1010         return params().getLyXTextClass().outputType() == LATEX;
1011 }
1012
1013
1014 bool Buffer::isLinuxDoc() const
1015 {
1016         return params().getLyXTextClass().outputType() == LINUXDOC;
1017 }
1018
1019
1020 bool Buffer::isLiterate() const
1021 {
1022         return params().getLyXTextClass().outputType() == LITERATE;
1023 }
1024
1025
1026 bool Buffer::isDocBook() const
1027 {
1028         return params().getLyXTextClass().outputType() == DOCBOOK;
1029 }
1030
1031
1032 bool Buffer::isSGML() const
1033 {
1034         LyXTextClass const & tclass = params().getLyXTextClass();
1035
1036         return tclass.outputType() == LINUXDOC ||
1037                tclass.outputType() == DOCBOOK;
1038 }
1039
1040
1041 void Buffer::makeLinuxDocFile(string const & fname,
1042                               OutputParams const & runparams,
1043                               bool body_only )
1044 {
1045         ofstream ofs;
1046         if (!openFileWrite(ofs, fname))
1047                 return;
1048
1049         niceFile() = runparams.nice; // this will be used by included files.
1050
1051         LaTeXFeatures features(*this, params());
1052
1053         validate(features);
1054
1055         texrow().reset();
1056
1057         LyXTextClass const & tclass = params().getLyXTextClass();
1058
1059         string top_element = tclass.latexname();
1060
1061         if (!body_only) {
1062                 ofs << "<!doctype linuxdoc system";
1063
1064                 string preamble = params().preamble;
1065                 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1066                          : fname;
1067                 preamble += features.getIncludedFiles(name);
1068                 preamble += features.getLyXSGMLEntities();
1069
1070                 if (!preamble.empty()) {
1071                         ofs << " [ " << preamble << " ]";
1072                 }
1073                 ofs << ">\n\n";
1074
1075                 if (params().options.empty())
1076                         sgml::openTag(ofs, 0, false, top_element);
1077                 else {
1078                         string top = top_element;
1079                         top += ' ';
1080                         top += params().options;
1081                         sgml::openTag(ofs, 0, false, top);
1082                 }
1083         }
1084
1085         ofs << "<!-- LyX "  << lyx_version
1086             << " created this file. For more info see http://www.lyx.org/"
1087             << " -->\n";
1088
1089         linuxdocParagraphs(*this, paragraphs(), ofs, runparams);
1090
1091         if (!body_only) {
1092                 ofs << "\n\n";
1093                 sgml::closeTag(ofs, 0, false, top_element);
1094         }
1095
1096         ofs.close();
1097         // How to check for successful close
1098
1099         // we want this to be true outside previews (for insetexternal)
1100         niceFile() = true;
1101 }
1102
1103
1104 void Buffer::makeDocBookFile(string const & fname,
1105                              OutputParams const & runparams,
1106                              bool only_body)
1107 {
1108         ofstream ofs;
1109         if (!openFileWrite(ofs, fname))
1110                 return;
1111
1112         niceFile() = runparams.nice; // this will be used by Insetincludes.
1113
1114         LaTeXFeatures features(*this, params());
1115         validate(features);
1116
1117         texrow().reset();
1118
1119         LyXTextClass const & tclass = params().getLyXTextClass();
1120         string top_element = tclass.latexname();
1121
1122         if (!only_body) {
1123                 ofs << "<!DOCTYPE " << top_element
1124                     << "  PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
1125
1126                 string preamble = params().preamble;
1127                 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1128                          : fname;
1129                 preamble += features.getIncludedFiles(name);
1130                 preamble += features.getLyXSGMLEntities();
1131
1132                 if (!preamble.empty()) {
1133                         ofs << "\n [ " << preamble << " ]";
1134                 }
1135                 ofs << ">\n\n";
1136         }
1137
1138         string top = top_element;
1139         top += " lang=\"";
1140         top += params().language->code();
1141         top += '"';
1142
1143         if (!params().options.empty()) {
1144                 top += ' ';
1145                 top += params().options;
1146         }
1147         sgml::openTag(ofs, 0, false, top);
1148
1149         ofs << "<!-- DocBook file was created by LyX " << lyx_version
1150             << "\n  See http://www.lyx.org/ for more information -->\n";
1151
1152         params().getLyXTextClass().counters().reset();
1153         docbookParagraphs(*this, paragraphs(), ofs, runparams);
1154
1155         ofs << "\n\n";
1156         sgml::closeTag(ofs, 0, false, top_element);
1157
1158         ofs.close();
1159         // How to check for successful close
1160
1161         // we want this to be true outside previews (for insetexternal)
1162         niceFile() = true;
1163 }
1164
1165
1166 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1167 // Other flags: -wall -v0 -x
1168 int Buffer::runChktex()
1169 {
1170         busy(true);
1171
1172         // get LaTeX-Filename
1173         string const name = getLatexName();
1174         string path = filePath();
1175
1176         string const org_path = path;
1177         if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
1178                 path = temppath();
1179         }
1180
1181         Path p(path); // path to LaTeX file
1182         message(_("Running chktex..."));
1183
1184         // Generate the LaTeX file if neccessary
1185         OutputParams runparams;
1186         runparams.flavor = OutputParams::LATEX;
1187         runparams.nice = false;
1188         makeLaTeXFile(name, org_path, runparams);
1189
1190         TeXErrors terr;
1191         Chktex chktex(lyxrc.chktex_command, name, filePath());
1192         int res = chktex.run(terr); // run chktex
1193
1194         if (res == -1) {
1195                 Alert::error(_("chktex failure"),
1196                              _("Could not run chktex successfully."));
1197         } else if (res > 0) {
1198                 // Insert all errors as errors boxes
1199                 bufferErrors(*this, terr);
1200         }
1201
1202         busy(false);
1203
1204         return res;
1205 }
1206
1207
1208 void Buffer::validate(LaTeXFeatures & features) const
1209 {
1210         LyXTextClass const & tclass = params().getLyXTextClass();
1211
1212         if (params().tracking_changes) {
1213                 features.require("dvipost");
1214                 features.require("color");
1215         }
1216
1217         // AMS Style is at document level
1218         if (params().use_amsmath == BufferParams::AMS_ON
1219             || tclass.provides(LyXTextClass::amsmath))
1220                 features.require("amsmath");
1221
1222         for_each(paragraphs().begin(), paragraphs().end(),
1223                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1224
1225         // the bullet shapes are buffer level not paragraph level
1226         // so they are tested here
1227         for (int i = 0; i < 4; ++i) {
1228                 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1229                         int const font = params().user_defined_bullet(i).getFont();
1230                         if (font == 0) {
1231                                 int const c = params()
1232                                         .user_defined_bullet(i)
1233                                         .getCharacter();
1234                                 if (c == 16
1235                                    || c == 17
1236                                    || c == 25
1237                                    || c == 26
1238                                    || c == 31) {
1239                                         features.require("latexsym");
1240                                 }
1241                         } else if (font == 1) {
1242                                 features.require("amssymb");
1243                         } else if ((font >= 2 && font <= 5)) {
1244                                 features.require("pifont");
1245                         }
1246                 }
1247         }
1248
1249         if (lyxerr.debugging(Debug::LATEX)) {
1250                 features.showStruct();
1251         }
1252 }
1253
1254
1255 void Buffer::getLabelList(std::vector<string> & list) const
1256 {
1257         /// if this is a child document and the parent is already loaded
1258         /// Use the parent's list instead  [ale990407]
1259         if (!params().parentname.empty()
1260             && bufferlist.exists(params().parentname)) {
1261                 Buffer const * tmp = bufferlist.getBuffer(params().parentname);
1262                 if (tmp) {
1263                         tmp->getLabelList(list);
1264                         return;
1265                 }
1266         }
1267
1268         for (inset_iterator it = inset_const_iterator_begin();
1269              it != inset_const_iterator_end(); ++it) {
1270                 it->getLabelList(*this, list);
1271         }
1272 }
1273
1274
1275 // This is also a buffer property (ale)
1276 void Buffer::fillWithBibKeys(std::vector<std::pair<string, string> > & keys) const
1277 {
1278         /// if this is a child document and the parent is already loaded
1279         /// use the parent's list instead  [ale990412]
1280         if (!params().parentname.empty() &&
1281             bufferlist.exists(params().parentname)) {
1282                 Buffer const * tmp = bufferlist.getBuffer(params().parentname);
1283                 if (tmp) {
1284                         tmp->fillWithBibKeys(keys);
1285                         return;
1286                 }
1287         }
1288
1289         for (inset_iterator it = inset_const_iterator_begin();
1290                 it != inset_const_iterator_end(); ++it) {
1291                 if (it->lyxCode() == InsetOld::BIBTEX_CODE) {
1292                         InsetBibtex const & inset =
1293                                 dynamic_cast<InsetBibtex const &>(*it);
1294                         inset.fillWithBibKeys(*this, keys);
1295                 } else if (it->lyxCode() == InsetOld::INCLUDE_CODE) {
1296                         InsetInclude const & inset =
1297                                 dynamic_cast<InsetInclude const &>(*it);
1298                         inset.fillWithBibKeys(*this, keys);
1299                 } else if (it->lyxCode() == InsetOld::BIBITEM_CODE) {
1300                         InsetBibitem const & inset =
1301                                 dynamic_cast<InsetBibitem const &>(*it);
1302                         string const key = inset.getContents();
1303                         string const opt = inset.getOptions();
1304                         string const ref; // = pit->asString(this, false);
1305                         string const info = opt + "TheBibliographyRef" + ref;
1306                         keys.push_back(pair<string, string>(key, info));
1307                 }
1308         }
1309 }
1310
1311
1312 bool Buffer::isDepClean(string const & name) const
1313 {
1314         DepClean::const_iterator it = pimpl_->dep_clean.find(name);
1315         if (it == pimpl_->dep_clean.end())
1316                 return true;
1317         return it->second;
1318 }
1319
1320
1321 void Buffer::markDepClean(string const & name)
1322 {
1323         pimpl_->dep_clean[name] = true;
1324 }
1325
1326
1327 bool Buffer::dispatch(string const & command, bool * result)
1328 {
1329         return dispatch(lyxaction.lookupFunc(command), result);
1330 }
1331
1332
1333 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1334 {
1335         bool dispatched = true;
1336
1337         switch (func.action) {
1338                 case LFUN_EXPORT: {
1339                         bool const tmp = Exporter::Export(this, func.argument, false);
1340                         if (result)
1341                                 *result = tmp;
1342                         break;
1343                 }
1344
1345                 default:
1346                         dispatched = false;
1347         }
1348         return dispatched;
1349 }
1350
1351
1352 void Buffer::changeLanguage(Language const * from, Language const * to)
1353 {
1354         lyxerr << "Changing Language!" << endl;
1355
1356         // Take care of l10n/i18n
1357         updateDocLang(to);
1358
1359         ParIterator end = par_iterator_end();
1360         for (ParIterator it = par_iterator_begin(); it != end; ++it)
1361                 it->changeLanguage(params(), from, to);
1362 }
1363
1364
1365 void Buffer::updateDocLang(Language const * nlang)
1366 {
1367         pimpl_->messages.reset(new Messages(nlang->code()));
1368 }
1369
1370
1371 bool Buffer::isMultiLingual()
1372 {
1373         ParIterator end = par_iterator_end();
1374         for (ParIterator it = par_iterator_begin(); it != end; ++it)
1375                 if (it->isMultiLingual(params()))
1376                         return true;
1377
1378         return false;
1379 }
1380
1381
1382 void Buffer::inset_iterator::setParagraph()
1383 {
1384         while (pit != pend) {
1385                 it = pit->insetlist.begin();
1386                 if (it != pit->insetlist.end())
1387                         return;
1388                 ++pit;
1389         }
1390 }
1391
1392
1393 ParIterator Buffer::getParFromID(int id) const
1394 {
1395 #warning FIXME: const correctness! (Andre)
1396         ParIterator it = const_cast<Buffer*>(this)->par_iterator_begin();
1397         ParIterator end = const_cast<Buffer*>(this)->par_iterator_end();
1398
1399 #warning FIXME, perhaps this func should return a ParIterator? (Lgb)
1400         if (id < 0) {
1401                 // John says this is called with id == -1 from undo
1402                 lyxerr << "getParFromID(), id: " << id << endl;
1403                 return end;
1404         }
1405
1406         for (; it != end; ++it)
1407                 if (it->id() == id)
1408                         return it;
1409
1410         return end;
1411 }
1412
1413
1414 bool Buffer::hasParWithID(int id) const
1415 {
1416         ParConstIterator it = par_iterator_begin();
1417         ParConstIterator end = par_iterator_end();
1418
1419         if (id < 0) {
1420                 // John says this is called with id == -1 from undo
1421                 lyxerr << "hasParWithID(), id: " << id << endl;
1422                 return 0;
1423         }
1424
1425         for (; it != end; ++it)
1426                 if (it->id() == id)
1427                         return true;
1428
1429         return false;
1430 }
1431
1432
1433 PosIterator Buffer::pos_iterator_begin()
1434 {
1435         return PosIterator(&paragraphs(), paragraphs().begin(), 0);
1436 }
1437
1438
1439 PosIterator Buffer::pos_iterator_end()
1440 {
1441         return PosIterator(&paragraphs(), paragraphs().end(), 0);
1442 }
1443
1444
1445 ParIterator Buffer::par_iterator_begin()
1446 {
1447         return ParIterator(paragraphs().begin(), paragraphs());
1448 }
1449
1450
1451 ParIterator Buffer::par_iterator_end()
1452 {
1453         return ParIterator(paragraphs().end(), paragraphs());
1454 }
1455
1456
1457 ParConstIterator Buffer::par_iterator_begin() const
1458 {
1459         ParagraphList const & pars = paragraphs();
1460         return ParConstIterator(const_cast<ParagraphList&>(pars).begin(), pars);
1461 }
1462
1463
1464 ParConstIterator Buffer::par_iterator_end() const
1465 {
1466         ParagraphList const & pars = paragraphs();
1467         return ParConstIterator(const_cast<ParagraphList&>(pars).end(), pars);
1468 }
1469
1470
1471 Language const * Buffer::getLanguage() const
1472 {
1473         return params().language;
1474 }
1475
1476
1477 string const Buffer::B_(string const & l10n) const
1478 {
1479         if (pimpl_->messages.get()) {
1480                 return pimpl_->messages->get(l10n);
1481         }
1482
1483         return _(l10n);
1484 }
1485
1486
1487 bool Buffer::isClean() const
1488 {
1489         return pimpl_->lyx_clean;
1490 }
1491
1492
1493 bool Buffer::isBakClean() const
1494 {
1495         return pimpl_->bak_clean;
1496 }
1497
1498
1499 void Buffer::markClean() const
1500 {
1501         if (!pimpl_->lyx_clean) {
1502                 pimpl_->lyx_clean = true;
1503                 updateTitles();
1504         }
1505         // if the .lyx file has been saved, we don't need an
1506         // autosave
1507         pimpl_->bak_clean = true;
1508 }
1509
1510
1511 void Buffer::markBakClean()
1512 {
1513         pimpl_->bak_clean = true;
1514 }
1515
1516
1517 void Buffer::setUnnamed(bool flag)
1518 {
1519         pimpl_->unnamed = flag;
1520 }
1521
1522
1523 bool Buffer::isUnnamed()
1524 {
1525         return pimpl_->unnamed;
1526 }
1527
1528
1529 void Buffer::markDirty()
1530 {
1531         if (pimpl_->lyx_clean) {
1532                 pimpl_->lyx_clean = false;
1533                 updateTitles();
1534         }
1535         pimpl_->bak_clean = false;
1536
1537         DepClean::iterator it = pimpl_->dep_clean.begin();
1538         DepClean::const_iterator const end = pimpl_->dep_clean.end();
1539
1540         for (; it != end; ++it) {
1541                 it->second = false;
1542         }
1543 }
1544
1545
1546 string const & Buffer::fileName() const
1547 {
1548         return pimpl_->filename;
1549 }
1550
1551
1552 string const & Buffer::filePath() const
1553 {
1554         return pimpl_->filepath;
1555 }
1556
1557
1558 bool Buffer::isReadonly() const
1559 {
1560         return pimpl_->read_only;
1561 }
1562
1563
1564 void Buffer::setParentName(string const & name)
1565 {
1566         params().parentname = name;
1567 }
1568
1569
1570 Buffer::inset_iterator::inset_iterator()
1571         : pit(), pend()
1572 {}
1573
1574
1575 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
1576         : pit(p), pend(e)
1577 {
1578         setParagraph();
1579 }
1580
1581
1582 Buffer::inset_iterator Buffer::inset_iterator_begin()
1583 {
1584         return inset_iterator(paragraphs().begin(), paragraphs().end());
1585 }
1586
1587
1588 Buffer::inset_iterator Buffer::inset_iterator_end()
1589 {
1590         return inset_iterator(paragraphs().end(), paragraphs().end());
1591 }
1592
1593
1594 Buffer::inset_iterator Buffer::inset_const_iterator_begin() const
1595 {
1596         ParagraphList & pars = const_cast<ParagraphList&>(paragraphs());
1597         return inset_iterator(pars.begin(), pars.end());
1598 }
1599
1600
1601 Buffer::inset_iterator Buffer::inset_const_iterator_end() const
1602 {
1603         ParagraphList & pars = const_cast<ParagraphList&>(paragraphs());
1604         return inset_iterator(pars.end(), pars.end());
1605 }
1606
1607
1608 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
1609 {
1610         if (pit != pend) {
1611                 ++it;
1612                 if (it == pit->insetlist.end()) {
1613                         ++pit;
1614                         setParagraph();
1615                 }
1616         }
1617         return *this;
1618 }
1619
1620
1621 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
1622 {
1623         inset_iterator tmp = *this;
1624         ++*this;
1625         return tmp;
1626 }
1627
1628
1629 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
1630 {
1631         return *it->inset;
1632 }
1633
1634
1635 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
1636 {
1637         return it->inset;
1638 }
1639
1640
1641 ParagraphList::iterator Buffer::inset_iterator::getPar() const
1642 {
1643         return pit;
1644 }
1645
1646
1647 lyx::pos_type Buffer::inset_iterator::getPos() const
1648 {
1649         return it->pos;
1650 }
1651
1652
1653 bool operator==(Buffer::inset_iterator const & iter1,
1654                 Buffer::inset_iterator const & iter2)
1655 {
1656         return iter1.pit == iter2.pit
1657                 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
1658 }
1659
1660
1661 bool operator!=(Buffer::inset_iterator const & iter1,
1662                 Buffer::inset_iterator const & iter2)
1663 {
1664         return !(iter1 == iter2);
1665 }