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