]> git.lyx.org Git - lyx.git/blob - src/buffer.C
fix bug 2090 (remove param \quotes_times). File format is up to 245 now.
[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         if (paragraphs().empty()) {
474                 readHeader(lex);
475                 if (!params().getLyXTextClass().load()) {
476                         string theclass = params().getLyXTextClass().name();
477                         Alert::error(_("Can't load document class"), bformat(
478                                         "Using the default document class, because the "
479                                         " class %1$s could not be loaded.", theclass));
480                         params().textclass = 0;
481                 }
482         } else {
483                 // We don't want to adopt the parameters from the
484                 // document we insert, so read them into a temporary buffer
485                 // and then discard it
486
487                 Buffer tmpbuf("", false);
488                 tmpbuf.readHeader(lex);
489         }
490
491         return text().read(*this, lex);
492 }
493
494
495 // needed to insert the selection
496 void Buffer::insertStringAsLines(ParagraphList & pars,
497         pit_type & pit, pos_type & pos,
498         LyXFont const & fn, string const & str, bool autobreakrows)
499 {
500         LyXFont font = fn;
501
502         // insert the string, don't insert doublespace
503         bool space_inserted = true;
504         for (string::const_iterator cit = str.begin();
505             cit != str.end(); ++cit) {
506                 Paragraph & par = pars[pit];
507                 if (*cit == '\n') {
508                         if (autobreakrows && (!par.empty() || par.allowEmpty())) {
509                                 breakParagraph(params(), pars, pit, pos,
510                                                par.layout()->isEnvironment());
511                                 ++pit;
512                                 pos = 0;
513                                 space_inserted = true;
514                         } else {
515                                 continue;
516                         }
517                         // do not insert consecutive spaces if !free_spacing
518                 } else if ((*cit == ' ' || *cit == '\t') &&
519                            space_inserted && !par.isFreeSpacing()) {
520                         continue;
521                 } else if (*cit == '\t') {
522                         if (!par.isFreeSpacing()) {
523                                 // tabs are like spaces here
524                                 par.insertChar(pos, ' ', font);
525                                 ++pos;
526                                 space_inserted = true;
527                         } else {
528                                 const pos_type n = 8 - pos % 8;
529                                 for (pos_type i = 0; i < n; ++i) {
530                                         par.insertChar(pos, ' ', font);
531                                         ++pos;
532                                 }
533                                 space_inserted = true;
534                         }
535                 } else if (!IsPrintable(*cit)) {
536                         // Ignore unprintables
537                         continue;
538                 } else {
539                         // just insert the character
540                         par.insertChar(pos, *cit, font);
541                         ++pos;
542                         space_inserted = (*cit == ' ');
543                 }
544
545         }
546 }
547
548
549 bool Buffer::readFile(string const & filename)
550 {
551         // Check if the file is compressed.
552         string const format = getFormatFromContents(filename);
553         if (format == "gzip" || format == "zip" || format == "compress") {
554                 params().compressed = true;
555         }
556
557         // remove dummy empty par
558         paragraphs().clear();
559         bool ret = readFile(filename, paragraphs().size());
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::readFile(string const & filename, pit_type const pit)
571 {
572         LyXLex lex(0, 0);
573         lex.setFile(filename);
574         return readFile(lex, filename, pit);
575 }
576
577
578 bool Buffer::fully_loaded() const
579 {
580         return pimpl_->file_fully_loaded;
581 }
582
583
584 void Buffer::fully_loaded(bool const value)
585 {
586         pimpl_->file_fully_loaded = value;
587 }
588
589
590 bool Buffer::readFile(LyXLex & lex, string const & filename, pit_type const pit)
591 {
592         BOOST_ASSERT(!filename.empty());
593
594         if (!lex.isOK()) {
595                 Alert::error(_("Document could not be read"),
596                              bformat(_("%1$s could not be read."), filename));
597                 return false;
598         }
599
600         lex.next();
601         string const token(lex.getString());
602
603         if (!lex.isOK()) {
604                 Alert::error(_("Document could not be read"),
605                              bformat(_("%1$s could not be read."), filename));
606                 return false;
607         }
608
609         // the first token _must_ be...
610         if (token != "\\lyxformat") {
611                 lyxerr << "Token: " << token << endl;
612
613                 Alert::error(_("Document format failure"),
614                              bformat(_("%1$s is not a LyX document."),
615                                        filename));
616                 return false;
617         }
618
619         lex.next();
620         string tmp_format = lex.getString();
621         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
622         // if present remove ".," from string.
623         string::size_type dot = tmp_format.find_first_of(".,");
624         //lyxerr << "           dot found at " << dot << endl;
625         if (dot != string::npos)
626                         tmp_format.erase(dot, 1);
627         int const file_format = convert<int>(tmp_format);
628         //lyxerr << "format: " << file_format << endl;
629
630         if (file_format != LYX_FORMAT) {
631                 string const tmpfile = tempName();
632                 if (tmpfile.empty()) {
633                         Alert::error(_("Conversion failed"),
634                                      bformat(_("%1$s is from an earlier"
635                                               " version of LyX, but a temporary"
636                                               " file for converting it could"
637                                               " not be created."),
638                                               filename));
639                         return false;
640                 }
641                 string const lyx2lyx = LibFileSearch("lyx2lyx", "lyx2lyx");
642                 if (lyx2lyx.empty()) {
643                         Alert::error(_("Conversion script not found"),
644                                      bformat(_("%1$s is from an earlier"
645                                                " version of LyX, but the"
646                                                " conversion script lyx2lyx"
647                                                " could not be found."),
648                                                filename));
649                         return false;
650                 }
651                 ostringstream command;
652                 command << "python " << QuoteName(lyx2lyx)
653                         << " -t " << convert<string>(LYX_FORMAT)
654                         << " -o " << QuoteName(tmpfile) << ' '
655                         << QuoteName(filename);
656                 string const command_str = command.str();
657
658                 lyxerr[Debug::INFO] << "Running '"
659                                     << command_str << '\''
660                                     << endl;
661
662                 cmd_ret const ret = RunCommand(command_str);
663                 if (ret.first != 0) {
664                         Alert::error(_("Conversion script failed"),
665                                      bformat(_("%1$s is from an earlier version"
666                                               " of LyX, but the lyx2lyx script"
667                                               " failed to convert it."),
668                                               filename));
669                         return false;
670                 } else {
671                         bool const ret = readFile(tmpfile, pit);
672                         // Do stuff with tmpfile name and buffer name here.
673                         return ret;
674                 }
675
676         }
677
678         if (readDocument(lex)) {
679                 Alert::error(_("Document format failure"),
680                              bformat(_("%1$s ended unexpectedly, which means"
681                                        " that it is probably corrupted."),
682                                        filename));
683         }
684
685         //lyxerr << "removing " << MacroTable::localMacros().size()
686         //      << " temporary macro entries" << endl;
687         //MacroTable::localMacros().clear();
688
689         pimpl_->file_fully_loaded = true;
690         return true;
691 }
692
693
694 // Should probably be moved to somewhere else: BufferView? LyXView?
695 bool Buffer::save() const
696 {
697         // We don't need autosaves in the immediate future. (Asger)
698         resetAutosaveTimers();
699
700         // make a backup
701         string s;
702         if (lyxrc.make_backup) {
703                 s = fileName() + '~';
704                 if (!lyxrc.backupdir_path.empty())
705                         s = AddName(lyxrc.backupdir_path,
706                                     subst(os::internal_path(s),'/','!'));
707
708                 // It might very well be that this variant is just
709                 // good enough. (Lgb)
710                 // But to use this we need fs::copy_file to actually do a copy,
711                 // even when the target file exists. (Lgb)
712                 if (fs::exists(fileName()) && fs::is_writable(fs::path(fileName()).branch_path())) {
713                   //try {
714                     fs::copy_file(fileName(), s, false);
715                     //}
716                     //catch (fs::filesystem_error const & fe) {
717                     //lyxerr << "LyX was not able to make backup copy. Beware.\n"
718                     //     << fe.what() << endl;
719                     //}
720                 }
721         }
722
723         if (writeFile(fileName())) {
724                 markClean();
725                 removeAutosaveFile(fileName());
726         } else {
727                 // Saving failed, so backup is not backup
728                 if (lyxrc.make_backup)
729                         rename(s, fileName());
730                 return false;
731         }
732         return true;
733 }
734
735
736 bool Buffer::writeFile(string const & fname) const
737 {
738         if (pimpl_->read_only && fname == fileName())
739                 return false;
740
741         bool retval = false;
742
743         if (params().compressed) {
744 #ifdef USE_COMPRESSION
745                 gz::ogzstream ofs(fname.c_str(), ios::out|ios::trunc);
746                 if (!ofs)
747                         return false;
748
749                 retval = do_writeFile(ofs);
750 #else
751                 return false;
752 #endif
753         } else {
754                 ofstream ofs(fname.c_str(), ios::out|ios::trunc);
755                 if (!ofs)
756                         return false;
757
758                 retval = do_writeFile(ofs);
759         }
760
761         return retval;
762 }
763
764
765 bool Buffer::do_writeFile(ostream & ofs) const
766 {
767 #ifdef HAVE_LOCALE
768         // Use the standard "C" locale for file output.
769         ofs.imbue(std::locale::classic());
770 #endif
771
772         // The top of the file should not be written by params().
773
774         // write out a comment in the top of the file
775         ofs << "#LyX " << lyx_version
776             << " created this file. For more info see http://www.lyx.org/\n"
777             << "\\lyxformat " << LYX_FORMAT << "\n"
778             << "\\begin_document\n";
779
780         // now write out the buffer parameters.
781         ofs << "\\begin_header\n";
782         params().writeFile(ofs);
783         ofs << "\\end_header\n";
784
785         // write the text
786         ofs << "\n\\begin_body\n";
787         text().write(*this, ofs);
788         ofs << "\n\\end_body\n";
789
790         // Write marker that shows file is complete
791         ofs << "\\end_document" << endl;
792
793         // Shouldn't really be needed....
794         //ofs.close();
795
796         // how to check if close went ok?
797         // Following is an attempt... (BE 20001011)
798
799         // good() returns false if any error occured, including some
800         //        formatting error.
801         // bad()  returns true if something bad happened in the buffer,
802         //        which should include file system full errors.
803
804         bool status = true;
805         if (!ofs) {
806                 status = false;
807                 lyxerr << "File was not closed properly." << endl;
808         }
809
810         return status;
811 }
812
813
814 void Buffer::makeLaTeXFile(string const & fname,
815                            string const & original_path,
816                            OutputParams const & runparams,
817                            bool output_preamble, bool output_body)
818 {
819         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
820
821         ofstream ofs;
822         if (!openFileWrite(ofs, fname))
823                 return;
824
825         makeLaTeXFile(ofs, original_path,
826                       runparams, output_preamble, output_body);
827
828         ofs.close();
829         if (ofs.fail())
830                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
831 }
832
833
834 void Buffer::makeLaTeXFile(ostream & os,
835                            string const & original_path,
836                            OutputParams const & runparams_in,
837                            bool const output_preamble, bool const output_body)
838 {
839         OutputParams runparams = runparams_in;
840
841         // validate the buffer.
842         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
843         LaTeXFeatures features(*this, params(), runparams.nice);
844         validate(features);
845         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
846
847         texrow().reset();
848
849         // The starting paragraph of the coming rows is the
850         // first paragraph of the document. (Asger)
851         texrow().start(paragraphs().begin()->id(), 0);
852
853         if (output_preamble && runparams.nice) {
854                 os << "%% LyX " << lyx_version << " created this file.  "
855                         "For more info, see http://www.lyx.org/.\n"
856                         "%% Do not edit unless you really know what "
857                         "you are doing.\n";
858                 texrow().newline();
859                 texrow().newline();
860         }
861         lyxerr[Debug::INFO] << "lyx document header finished" << endl;
862         // There are a few differences between nice LaTeX and usual files:
863         // usual is \batchmode and has a
864         // special input@path to allow the including of figures
865         // with either \input or \includegraphics (what figinsets do).
866         // input@path is set when the actual parameter
867         // original_path is set. This is done for usual tex-file, but not
868         // for nice-latex-file. (Matthias 250696)
869         // Note that input@path is only needed for something the user does
870         // in the preamble, included .tex files or ERT, files included by
871         // LyX work without it.
872         if (output_preamble) {
873                 if (!runparams.nice) {
874                         // code for usual, NOT nice-latex-file
875                         os << "\\batchmode\n"; // changed
876                         // from \nonstopmode
877                         texrow().newline();
878                 }
879                 if (!original_path.empty()) {
880                         string const inputpath = latex_path(original_path);
881                         os << "\\makeatletter\n"
882                             << "\\def\\input@path{{"
883                             << inputpath << "/}}\n"
884                             << "\\makeatother\n";
885                         texrow().newline();
886                         texrow().newline();
887                         texrow().newline();
888                 }
889
890                 // Write the preamble
891                 runparams.use_babel = params().writeLaTeX(os, features, texrow());
892
893                 if (!output_body)
894                         return;
895
896                 // make the body.
897                 os << "\\begin{document}\n";
898                 texrow().newline();
899         } // output_preamble
900         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
901
902         if (!lyxrc.language_auto_begin) {
903                 os << subst(lyxrc.language_command_begin, "$$lang",
904                              params().language->babel())
905                     << endl;
906                 texrow().newline();
907         }
908
909         // if we are doing a real file with body, even if this is the
910         // child of some other buffer, let's cut the link here.
911         // This happens for example if only a child document is printed.
912         string save_parentname;
913         if (output_preamble) {
914                 save_parentname = params().parentname;
915                 params().parentname.erase();
916         }
917
918         // the real stuff
919         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
920
921         // Restore the parenthood if needed
922         if (output_preamble)
923                 params().parentname = save_parentname;
924
925         // add this just in case after all the paragraphs
926         os << endl;
927         texrow().newline();
928
929         if (!lyxrc.language_auto_end) {
930                 os << subst(lyxrc.language_command_end, "$$lang",
931                              params().language->babel())
932                     << endl;
933                 texrow().newline();
934         }
935
936         if (output_preamble) {
937                 os << "\\end{document}\n";
938                 texrow().newline();
939
940                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
941         } else {
942                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
943                                      << endl;
944         }
945
946         // Just to be sure. (Asger)
947         texrow().newline();
948
949         lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
950         lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
951                             << '.' << endl;
952 }
953
954
955 bool Buffer::isLatex() const
956 {
957         return params().getLyXTextClass().outputType() == LATEX;
958 }
959
960
961 bool Buffer::isLinuxDoc() const
962 {
963         return params().getLyXTextClass().outputType() == LINUXDOC;
964 }
965
966
967 bool Buffer::isLiterate() const
968 {
969         return params().getLyXTextClass().outputType() == LITERATE;
970 }
971
972
973 bool Buffer::isDocBook() const
974 {
975         return params().getLyXTextClass().outputType() == DOCBOOK;
976 }
977
978
979 bool Buffer::isSGML() const
980 {
981         LyXTextClass const & tclass = params().getLyXTextClass();
982
983         return tclass.outputType() == LINUXDOC ||
984                tclass.outputType() == DOCBOOK;
985 }
986
987
988 void Buffer::makeLinuxDocFile(string const & fname,
989                               OutputParams const & runparams,
990                               bool const body_only)
991 {
992         ofstream ofs;
993         if (!openFileWrite(ofs, fname))
994                 return;
995
996         LaTeXFeatures features(*this, params(), runparams.nice);
997         validate(features);
998
999         texrow().reset();
1000
1001         LyXTextClass const & tclass = params().getLyXTextClass();
1002
1003         string const & top_element = tclass.latexname();
1004
1005         if (!body_only) {
1006                 ofs << tclass.class_header();
1007
1008                 string preamble = params().preamble;
1009                 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1010                          : fname;
1011                 preamble += features.getIncludedFiles(name);
1012                 preamble += features.getLyXSGMLEntities();
1013
1014                 if (!preamble.empty()) {
1015                         ofs << " [ " << preamble << " ]";
1016                 }
1017                 ofs << ">\n\n";
1018
1019                 if (params().options.empty())
1020                         sgml::openTag(ofs, top_element);
1021                 else {
1022                         string top = top_element;
1023                         top += ' ';
1024                         top += params().options;
1025                         sgml::openTag(ofs, top);
1026                 }
1027         }
1028
1029         ofs << "<!-- LyX "  << lyx_version
1030             << " created this file. For more info see http://www.lyx.org/"
1031             << " -->\n";
1032
1033         linuxdocParagraphs(*this, paragraphs(), ofs, runparams);
1034
1035         if (!body_only) {
1036                 ofs << "\n\n";
1037                 sgml::closeTag(ofs, top_element);
1038         }
1039
1040         ofs.close();
1041         if (ofs.fail())
1042                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1043 }
1044
1045
1046 void Buffer::makeDocBookFile(string const & fname,
1047                              OutputParams const & runparams,
1048                              bool const only_body)
1049 {
1050         ofstream ofs;
1051         if (!openFileWrite(ofs, fname))
1052                 return;
1053
1054         LaTeXFeatures features(*this, params(), runparams.nice);
1055         validate(features);
1056
1057         texrow().reset();
1058
1059         LyXTextClass const & tclass = params().getLyXTextClass();
1060         string const & top_element = tclass.latexname();
1061
1062         if (!only_body) {
1063                 if (runparams.flavor == OutputParams::XML)
1064                         ofs << "<?xml version=\"1.0\" encoding=\""
1065                             << params().language->encoding()->Name() << "\"?>\n";
1066
1067                 ofs << "<!DOCTYPE " << top_element << " ";
1068
1069                 if (! tclass.class_header().empty()) ofs << tclass.class_header();
1070                 else if (runparams.flavor == OutputParams::XML)
1071                         ofs << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1072                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1073                 else
1074                         ofs << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1075
1076                 string preamble = params().preamble;
1077                 if (runparams.flavor != OutputParams::XML ) {
1078                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1079                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1080                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1081                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1082                 }
1083
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
1108         ofs << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1109             << " file was created by LyX " << lyx_version
1110             << "\n  See http://www.lyx.org/ for more information -->\n";
1111
1112         params().getLyXTextClass().counters().reset();
1113
1114         sgml::openTag(ofs, top);
1115         ofs << '\n';
1116         docbookParagraphs(paragraphs(), *this, ofs, runparams);
1117         sgml::closeTag(ofs, 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 const 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 (features.isAvailable("dvipost") && params().tracking_changes
1168                 && params().output_changes) {
1169                 features.require("dvipost");
1170                 features.require("color");
1171         }
1172
1173         // AMS Style is at document level
1174         if (params().use_amsmath == BufferParams::AMS_ON
1175             || tclass.provides(LyXTextClass::amsmath))
1176                 features.require("amsmath");
1177
1178         for_each(paragraphs().begin(), paragraphs().end(),
1179                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1180
1181         // the bullet shapes are buffer level not paragraph level
1182         // so they are tested here
1183         for (int i = 0; i < 4; ++i) {
1184                 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1185                         int const font = params().user_defined_bullet(i).getFont();
1186                         if (font == 0) {
1187                                 int const c = params()
1188                                         .user_defined_bullet(i)
1189                                         .getCharacter();
1190                                 if (c == 16
1191                                    || c == 17
1192                                    || c == 25
1193                                    || c == 26
1194                                    || c == 31) {
1195                                         features.require("latexsym");
1196                                 }
1197                         } else if (font == 1) {
1198                                 features.require("amssymb");
1199                         } else if ((font >= 2 && font <= 5)) {
1200                                 features.require("pifont");
1201                         }
1202                 }
1203         }
1204
1205         if (lyxerr.debugging(Debug::LATEX)) {
1206                 features.showStruct();
1207         }
1208 }
1209
1210
1211 void Buffer::getLabelList(vector<string> & list) const
1212 {
1213         /// if this is a child document and the parent is already loaded
1214         /// Use the parent's list instead  [ale990407]
1215         Buffer const * tmp = getMasterBuffer();
1216         if (!tmp) {
1217                 lyxerr << "getMasterBuffer() failed!" << endl;
1218                 BOOST_ASSERT(tmp);
1219         }
1220         if (tmp != this) {
1221                 tmp->getLabelList(list);
1222                 return;
1223         }
1224
1225         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1226                 it.nextInset()->getLabelList(*this, list);
1227 }
1228
1229
1230 // This is also a buffer property (ale)
1231 void Buffer::fillWithBibKeys(vector<pair<string, string> > & keys)
1232         const
1233 {
1234         /// if this is a child document and the parent is already loaded
1235         /// use the parent's list instead  [ale990412]
1236         Buffer const * tmp = getMasterBuffer();
1237         BOOST_ASSERT(tmp);
1238         if (tmp != this) {
1239                 tmp->fillWithBibKeys(keys);
1240                 return;
1241         }
1242
1243         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1244                 if (it->lyxCode() == InsetBase::BIBTEX_CODE) {
1245                         InsetBibtex const & inset =
1246                                 dynamic_cast<InsetBibtex const &>(*it);
1247                         inset.fillWithBibKeys(*this, keys);
1248                 } else if (it->lyxCode() == InsetBase::INCLUDE_CODE) {
1249                         InsetInclude const & inset =
1250                                 dynamic_cast<InsetInclude const &>(*it);
1251                         inset.fillWithBibKeys(*this, keys);
1252                 } else if (it->lyxCode() == InsetBase::BIBITEM_CODE) {
1253                         InsetBibitem const & inset =
1254                                 dynamic_cast<InsetBibitem const &>(*it);
1255                         string const key = inset.getContents();
1256                         string const opt = inset.getOptions();
1257                         string const ref; // = pit->asString(this, false);
1258                         string const info = opt + "TheBibliographyRef" + ref;
1259                         keys.push_back(pair<string, string>(key, info));
1260                 }
1261         }
1262 }
1263
1264
1265 bool Buffer::isDepClean(string const & name) const
1266 {
1267         DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1268         if (it == pimpl_->dep_clean.end())
1269                 return true;
1270         return it->second;
1271 }
1272
1273
1274 void Buffer::markDepClean(string const & name)
1275 {
1276         pimpl_->dep_clean[name] = true;
1277 }
1278
1279
1280 bool Buffer::dispatch(string const & command, bool * result)
1281 {
1282         return dispatch(lyxaction.lookupFunc(command), result);
1283 }
1284
1285
1286 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1287 {
1288         bool dispatched = true;
1289
1290         switch (func.action) {
1291                 case LFUN_EXPORT: {
1292                         bool const tmp = Exporter::Export(this, func.argument, false);
1293                         if (result)
1294                                 *result = tmp;
1295                         break;
1296                 }
1297
1298                 default:
1299                         dispatched = false;
1300         }
1301         return dispatched;
1302 }
1303
1304
1305 void Buffer::changeLanguage(Language const * from, Language const * to)
1306 {
1307         BOOST_ASSERT(from);
1308         BOOST_ASSERT(to);
1309
1310         lyxerr << "Changing Language!" << endl;
1311
1312         // Take care of l10n/i18n
1313         updateDocLang(to);
1314
1315         for_each(par_iterator_begin(),
1316                  par_iterator_end(),
1317                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
1318 }
1319
1320
1321 void Buffer::updateDocLang(Language const * nlang)
1322 {
1323         BOOST_ASSERT(nlang);
1324
1325         pimpl_->messages.reset(new Messages(nlang->code()));
1326 }
1327
1328
1329 bool Buffer::isMultiLingual() const
1330 {
1331         ParConstIterator end = par_iterator_end();
1332         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1333                 if (it->isMultiLingual(params()))
1334                         return true;
1335
1336         return false;
1337 }
1338
1339
1340 ParIterator Buffer::getParFromID(int const id) const
1341 {
1342         ParConstIterator it = par_iterator_begin();
1343         ParConstIterator const end = par_iterator_end();
1344
1345         if (id < 0) {
1346                 // John says this is called with id == -1 from undo
1347                 lyxerr << "getParFromID(), id: " << id << endl;
1348                 return end;
1349         }
1350
1351         for (; it != end; ++it)
1352                 if (it->id() == id)
1353                         return it;
1354
1355         return end;
1356 }
1357
1358
1359 bool Buffer::hasParWithID(int const id) const
1360 {
1361         ParConstIterator const it = getParFromID(id);
1362         return it != par_iterator_end();
1363 }
1364
1365
1366 ParIterator Buffer::par_iterator_begin()
1367 {
1368         return ::par_iterator_begin(inset());
1369 }
1370
1371
1372 ParIterator Buffer::par_iterator_end()
1373 {
1374         return ::par_iterator_end(inset());
1375 }
1376
1377
1378 ParConstIterator Buffer::par_iterator_begin() const
1379 {
1380         return ::par_const_iterator_begin(inset());
1381 }
1382
1383
1384 ParConstIterator Buffer::par_iterator_end() const
1385 {
1386         return ::par_const_iterator_end(inset());
1387 }
1388
1389
1390 Language const * Buffer::getLanguage() const
1391 {
1392         return params().language;
1393 }
1394
1395
1396 string const Buffer::B_(string const & l10n) const
1397 {
1398         if (pimpl_->messages.get()) {
1399                 return pimpl_->messages->get(l10n);
1400         }
1401
1402         return _(l10n);
1403 }
1404
1405
1406 bool Buffer::isClean() const
1407 {
1408         return pimpl_->lyx_clean;
1409 }
1410
1411
1412 bool Buffer::isBakClean() const
1413 {
1414         return pimpl_->bak_clean;
1415 }
1416
1417
1418 void Buffer::markClean() const
1419 {
1420         if (!pimpl_->lyx_clean) {
1421                 pimpl_->lyx_clean = true;
1422                 updateTitles();
1423         }
1424         // if the .lyx file has been saved, we don't need an
1425         // autosave
1426         pimpl_->bak_clean = true;
1427 }
1428
1429
1430 void Buffer::markBakClean()
1431 {
1432         pimpl_->bak_clean = true;
1433 }
1434
1435
1436 void Buffer::setUnnamed(bool flag)
1437 {
1438         pimpl_->unnamed = flag;
1439 }
1440
1441
1442 bool Buffer::isUnnamed() const
1443 {
1444         return pimpl_->unnamed;
1445 }
1446
1447
1448 #ifdef WITH_WARNINGS
1449 #warning this function should be moved to buffer_pimpl.C
1450 #endif
1451 void Buffer::markDirty()
1452 {
1453         if (pimpl_->lyx_clean) {
1454                 pimpl_->lyx_clean = false;
1455                 updateTitles();
1456         }
1457         pimpl_->bak_clean = false;
1458
1459         DepClean::iterator it = pimpl_->dep_clean.begin();
1460         DepClean::const_iterator const end = pimpl_->dep_clean.end();
1461
1462         for (; it != end; ++it) {
1463                 it->second = false;
1464         }
1465 }
1466
1467
1468 string const & Buffer::fileName() const
1469 {
1470         return pimpl_->filename;
1471 }
1472
1473
1474 string const & Buffer::filePath() const
1475 {
1476         return pimpl_->filepath;
1477 }
1478
1479
1480 bool Buffer::isReadonly() const
1481 {
1482         return pimpl_->read_only;
1483 }
1484
1485
1486 void Buffer::setParentName(string const & name)
1487 {
1488         params().parentname = name;
1489 }
1490
1491
1492 Buffer const * Buffer::getMasterBuffer() const
1493 {
1494         if (!params().parentname.empty()
1495             && bufferlist.exists(params().parentname)) {
1496                 Buffer const * buf = bufferlist.getBuffer(params().parentname);
1497                 if (buf)
1498                         return buf->getMasterBuffer();
1499         }
1500
1501         return this;
1502 }
1503
1504
1505 MacroData const & Buffer::getMacro(std::string const & name) const
1506 {
1507         return pimpl_->macros.get(name);
1508 }
1509
1510
1511 bool Buffer::hasMacro(string const & name) const
1512 {
1513         return pimpl_->macros.has(name);
1514 }
1515
1516
1517 void Buffer::insertMacro(string const & name, MacroData const & data)
1518 {
1519         MacroTable::globalMacros().insert(name, data);
1520         pimpl_->macros.insert(name, data);
1521 }
1522
1523
1524 void Buffer::buildMacros()
1525 {
1526         // Start with global table.
1527         pimpl_->macros = MacroTable::globalMacros();
1528
1529         // Now add our own.
1530         ParagraphList const & pars = text().paragraphs();
1531         for (size_t i = 0, n = pars.size(); i != n; ++i) {
1532                 //lyxerr << "searching main par " << i
1533                 //      << " for macro definitions" << std::endl;
1534                 InsetList const & insets = pars[i].insetlist;
1535                 InsetList::const_iterator it = insets.begin();
1536                 InsetList::const_iterator end = insets.end();
1537                 for ( ; it != end; ++it) {
1538                         //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1539                         if (it->inset->lyxCode() == InsetBase::MATHMACRO_CODE) {
1540                                 MathMacroTemplate const & mac
1541                                         = static_cast<MathMacroTemplate const &>(*it->inset);
1542                                 insertMacro(mac.name(), mac.asMacroData());
1543                         }
1544                 }
1545         }
1546 }
1547
1548
1549 void Buffer::saveCursor(StableDocIterator cur, StableDocIterator anc)
1550 {
1551         cursor_ = cur;
1552         anchor_ = anc;
1553 }
1554
1555
1556 void Buffer::changeRefsIfUnique(string const & from, string const & to)
1557 {
1558         // Check if the label 'from' appears more than once
1559         vector<string> labels;
1560         getLabelList(labels);
1561
1562         if (lyx::count(labels.begin(), labels.end(), from) > 1)
1563                 return;
1564
1565         InsetBase::Code code = InsetBase::REF_CODE;
1566
1567         ParIterator it = par_iterator_begin();
1568         ParIterator end = par_iterator_end();
1569         for ( ; it != end; ++it) {
1570                 bool changed_inset = false;
1571                 for (InsetList::iterator it2 = it->insetlist.begin();
1572                      it2 != it->insetlist.end(); ++it2) {
1573                         if (it2->inset->lyxCode() == code) {
1574                                 InsetCommand * inset = static_cast<InsetCommand *>(it2->inset);
1575                                 if (inset->getContents() == from) {
1576                                         inset->setContents(to);
1577                                         //inset->setButtonLabel();
1578                                         changed_inset = true;
1579                                 }
1580                         }
1581                 }
1582         }
1583 }
1584