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