]> git.lyx.org Git - lyx.git/blob - src/Buffer.h
697994c9854009feee0adb325348fa0894ab65fc
[lyx.git] / src / Buffer.h
1 // -*- C++ -*-
2 /**
3  * \file Buffer.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Lars Gullik Bjønnes
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #ifndef BUFFER_H
13 #define BUFFER_H
14
15 #include "insets/InsetCode.h"
16
17 #include "support/strfwd.h"
18 #include "support/types.h"
19 #include "support/SignalSlot.h"
20
21 #include <string>
22 #include <vector>
23
24
25 namespace lyx {
26
27 class BiblioInfo;
28 class BufferParams;
29 class BufferSet;
30 class DocIterator;
31 class ErrorItem;
32 class ErrorList;
33 class FuncRequest;
34 class Inset;
35 class InsetRef;
36 class InsetLabel;
37 class Font;
38 class Format;
39 class Lexer;
40 class LyXRC;
41 class Text;
42 class LyXVC;
43 class LaTeXFeatures;
44 class Language;
45 class MacroData;
46 class MacroNameSet;
47 class MacroSet;
48 class OutputParams;
49 class Paragraph;
50 class ParConstIterator;
51 class ParIterator;
52 class ParagraphList;
53 class TeXErrors;
54 class TexRow;
55 class TocBackend;
56 class Undo;
57
58 namespace frontend {
59 class GuiBufferDelegate;
60 class WorkAreaManager;
61 }
62
63 namespace support {
64 class FileName;
65 class FileNameList;
66 }
67
68 /** The buffer object.
69  * This is the buffer object. It contains all the informations about
70  * a document loaded into LyX.
71  * The buffer object owns the Text (wrapped in an InsetText), which
72  * contains the individual paragraphs of the document.
73  *
74  *
75  * I am not sure if the class is complete or
76  * minimal, probably not.
77  * \author Lars Gullik Bjønnes
78  */
79 class Buffer {
80 public:
81         /// What type of log will \c getLogName() return?
82         enum LogType {
83                 latexlog, ///< LaTeX log
84                 buildlog  ///< Literate build log
85         };
86
87         /// Result of \c readFile()
88         enum ReadStatus {
89                 failure, ///< The file could not be read
90                 success, ///< The file could not be read
91                 wrongversion ///< The version of the file does not match ours
92         };
93
94
95         /// Method to check if a file is externally modified, used by
96         /// isExternallyModified()
97         /**
98          * timestamp is fast but inaccurate. For example, the granularity
99          * of timestamp on a FAT filesystem is 2 second. Also, various operations
100          * may touch the timestamp of a file even when its content is unchanged.
101          *
102          * checksum is accurate but slow, which can be a problem when it is
103          * frequently used, or used for a large file on a slow (network) file
104          * system.
105          *
106          * FIXME: replace this method with support/FileMonitor.
107          */
108         enum CheckMethod {
109                 checksum_method,  ///< Use file checksum
110                 timestamp_method, ///< Use timestamp, and checksum if timestamp has changed
111         };
112
113         /** Constructor
114             \param file
115             \param b  optional \c false by default
116         */
117         explicit Buffer(std::string const & file, bool b = false);
118
119         /// Destructor
120         ~Buffer();
121
122         /** High-level interface to buffer functionality.
123             This function parses a command string and executes it
124         */
125         bool dispatch(std::string const & command, bool * result = 0);
126
127         /// Maybe we know the function already by number...
128         bool dispatch(FuncRequest const & func, bool * result = 0);
129
130         /// Load the autosaved file.
131         void loadAutoSaveFile();
132
133         /// read a new document from a string
134         bool readString(std::string const &);
135         /// load a new file
136         bool readFile(support::FileName const & filename);
137
138         /// read the header, returns number of unknown tokens
139         int readHeader(Lexer & lex);
140
141         /** Reads a file without header.
142             \param par if != 0 insert the file.
143             \return \c false if file is not completely read.
144         */
145         bool readDocument(Lexer &);
146
147         ///
148         void insertStringAsLines(ParagraphList & plist,
149                 pit_type &, pos_type &,
150                 Font const &, docstring const &, bool);
151         ///
152         DocIterator getParFromID(int id) const;
153         /// do we have a paragraph with this id?
154         bool hasParWithID(int id) const;
155
156         ///
157         frontend::WorkAreaManager & workAreaManager() const;
158
159         /** Save file.
160             Takes care of auto-save files and backup file if requested.
161             Returns \c true if the save is successful, \c false otherwise.
162         */
163         bool save() const;
164
165         /// Write document to stream. Returns \c false if unsuccesful.
166         bool write(std::ostream &) const;
167         /// Write file. Returns \c false if unsuccesful.
168         bool writeFile(support::FileName const &) const;
169
170   /// Loads LyX file \c filename into buffer, *  and \return success
171         bool loadLyXFile(support::FileName const & s);
172
173         /// Fill in the ErrorList with the TeXErrors
174         void bufferErrors(TeXErrors const &, ErrorList &) const;
175
176         /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
177         bool makeLaTeXFile(support::FileName const & filename,
178                            std::string const & original_path,
179                            OutputParams const &,
180                            bool output_preamble = true,
181                            bool output_body = true) const;
182         /** Export the buffer to LaTeX.
183             If \p os is a file stream, and params().inputenc is "auto" or
184             "default", and the buffer contains text in different languages
185             with more than one encoding, then this method will change the
186             encoding associated to \p os. Therefore you must not call this
187             method with a string stream if the output is supposed to go to a
188             file. \code
189             ofdocstream ofs;
190             ofs.open("test.tex");
191             writeLaTeXSource(ofs, ...);
192             ofs.close();
193             \endcode is NOT equivalent to \code
194             odocstringstream oss;
195             writeLaTeXSource(oss, ...);
196             ofdocstream ofs;
197             ofs.open("test.tex");
198             ofs << oss.str();
199             ofs.close();
200             \endcode
201          */
202         void writeLaTeXSource(odocstream & os,
203                            std::string const & original_path,
204                            OutputParams const &,
205                            bool output_preamble = true,
206                            bool output_body = true) const;
207         ///
208         void makeDocBookFile(support::FileName const & filename,
209                              OutputParams const & runparams_in,
210                              bool only_body = false) const;
211         ///
212         void writeDocBookSource(odocstream & os, std::string const & filename,
213                              OutputParams const & runparams_in,
214                              bool only_body = false) const;
215         /// returns the main language for the buffer (document)
216         Language const * language() const;
217         /// get l10n translated to the buffers language
218         docstring const B_(std::string const & l10n) const;
219
220         ///
221         int runChktex();
222         /// return true if the main lyx file does not need saving
223         bool isClean() const;
224         ///
225         bool isBakClean() const;
226         ///
227         bool isDepClean(std::string const & name) const;
228
229         /// whether or not disk file has been externally modified
230         bool isExternallyModified(CheckMethod method) const;
231
232         /// save timestamp and checksum of the given file.
233         void saveCheckSum(support::FileName const & file) const;
234
235         /// mark the main lyx file as not needing saving
236         void markClean() const;
237
238         ///
239         void markBakClean() const;
240
241         ///
242         void markDepClean(std::string const & name);
243
244         ///
245         void setUnnamed(bool flag = true);
246
247         ///
248         bool isUnnamed() const;
249
250         /// Mark this buffer as dirty.
251         void markDirty();
252
253         /// Returns the buffer's filename. It is always an absolute path.
254         support::FileName fileName() const;
255
256         /// Returns the buffer's filename. It is always an absolute path.
257         std::string absFileName() const;
258
259         /// Returns the the path where the buffer lives.
260         /// It is always an absolute path.
261         std::string filePath() const;
262
263         /** A transformed version of the file name, adequate for LaTeX.
264             \param no_path optional if \c true then the path is stripped.
265         */
266         std::string latexName(bool no_path = true) const;
267
268         /// Get thee name and type of the log.
269         std::string logName(LogType * type = 0) const;
270
271         /// Change name of buffer. Updates "read-only" flag.
272         void setFileName(std::string const & newfile);
273
274         /// Set document's parent Buffer.
275         void setParent(Buffer const *);
276         Buffer const * parent() const;
277
278         // Collect all relative buffer
279         std::vector<Buffer const *> allRelatives() const;
280
281         /** Get the document's master (or \c this if this is not a
282             child document)
283          */
284         Buffer const * masterBuffer() const;
285
286         /// \return true if \p child is a child of this \c Buffer.
287         bool isChild(Buffer * child) const;
288
289         /// Is buffer read-only?
290         bool isReadonly() const;
291
292         /// Set buffer read-only flag
293         void setReadonly(bool flag = true);
294
295         /// returns \c true if the buffer contains a LaTeX document
296         bool isLatex() const;
297         /// returns \c true if the buffer contains a DocBook document
298         bool isDocBook() const;
299         /// returns \c true if the buffer contains a Wed document
300         bool isLiterate() const;
301
302         /** Validate a buffer for LaTeX.
303             This validates the buffer, and returns a struct for use by
304             #makeLaTeX# and others. Its main use is to figure out what
305             commands and packages need to be included in the LaTeX file.
306             It (should) also check that the needed constructs are there
307             (i.e. that the \refs points to coresponding \labels). It
308             should perhaps inset "error" insets to help the user correct
309             obvious mistakes.
310         */
311         void validate(LaTeXFeatures &) const;
312
313         /// Update the cache with all bibfiles in use (including bibfiles
314         /// of loaded child documents).
315         void updateBibfilesCache() const;
316         ///
317         void invalidateBibinfoCache();
318         /// Return the cache with all bibfiles in use (including bibfiles
319         /// of loaded child documents).
320         support::FileNameList const & getBibfilesCache() const;
321         /// \return the bibliography information for this buffer's master,
322         /// or just for it, if it isn't a child.
323         BiblioInfo const & masterBibInfo() const;
324         /// \return the bibliography information for this buffer ONLY.
325         BiblioInfo const & localBibInfo() const;
326         ///
327         void getLabelList(std::vector<docstring> &) const;
328
329         ///
330         void changeLanguage(Language const * from, Language const * to);
331
332         ///
333         bool isMultiLingual() const;
334
335         ///
336         BufferParams & params();
337         BufferParams const & params() const;
338
339         /** The list of paragraphs.
340             This is a linked list of paragraph, this list holds the
341             whole contents of the document.
342          */
343         ParagraphList & paragraphs();
344         ParagraphList const & paragraphs() const;
345
346         /// LyX version control object.
347         LyXVC & lyxvc();
348         LyXVC const & lyxvc() const;
349
350         /// Where to put temporary files.
351         std::string const temppath() const;
352
353         /// Used when typesetting to place errorboxes.
354         TexRow const & texrow() const;
355         TexRow & texrow();
356
357         ///
358         ParIterator par_iterator_begin();
359         ///
360         ParConstIterator par_iterator_begin() const;
361         ///
362         ParIterator par_iterator_end();
363         ///
364         ParConstIterator par_iterator_end() const;
365
366         // Position of the child buffer where it appears first in the master.
367         DocIterator firstChildPosition(Buffer const * child);
368
369         /** \returns true only when the file is fully loaded.
370          *  Used to prevent the premature generation of previews
371          *  and by the citation inset.
372          */
373         bool isFullyLoaded() const;
374         /// Set by buffer_funcs' newFile.
375         void setFullyLoaded(bool);
376
377         /// Our main text (inside the top InsetText)
378         Text & text() const;
379
380         /// Our top InsetText
381         Inset & inset() const;
382
383         //
384         // Macro handling
385         //
386         /// Collect macro definitions in paragraphs
387         void updateMacros() const;
388         /// Iterate through the whole buffer and try to resolve macros
389         void updateMacroInstances() const;
390
391         /// List macro names of this buffer, the parent and the children
392         void listMacroNames(MacroNameSet & macros) const;
393         /// Collect macros of the parent and its children in front of this buffer.
394         void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
395
396         /// Return macro defined before pos (or in the master buffer)
397         MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
398         /// Return macro defined anywhere in the buffer (or in the master buffer)
399         MacroData const * getMacro(docstring const & name, bool global = true) const;
400         /// Return macro defined before the inclusion of the child
401         MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
402
403         /// Replace the inset contents for insets which InsetCode is equal
404         /// to the passed \p inset_code.
405         void changeRefsIfUnique(docstring const & from, docstring const & to,
406                 InsetCode code);
407
408         /// get source code (latex/docbook) for some paragraphs, or all paragraphs
409         /// including preamble
410         void getSourceCode(odocstream & os, pit_type par_begin, pit_type par_end,
411                 bool full_source) const;
412
413         /// Access to error list.
414         /// This method is used only for GUI visualisation of Buffer related
415         /// errors (like parsing or LateX compilation). This method is const
416         /// because modifying the returned ErrorList does not touch the document
417         /// contents.
418         ErrorList & errorList(std::string const & type) const;
419
420         /// The Toc backend.
421         /// This is useful only for screen visualisation of the Buffer. This
422         /// method is const because modifying this backend does not touch
423         /// the document contents.
424         TocBackend & tocBackend() const;
425
426         ///
427         Undo & undo();
428
429         /// This function is called when the buffer is changed.
430         void changed() const;
431         ///
432         void updateTocItem(std::string const &, DocIterator const &) const;
433         /// This function is called when the buffer structure is changed.
434         void structureChanged() const;
435         /// This function is called when some parsing error shows up.
436         void errors(std::string const & err) const;
437         /// This function is called when the buffer busy status change.
438         void setBusy(bool on) const;
439         /// This function is called when the buffer readonly status change.
440         void setReadOnly(bool on) const;
441         /// Update window titles of all users.
442         void updateTitles() const;
443         /// Reset autosave timers for all users.
444         void resetAutosaveTimers() const;
445         ///
446         void message(docstring const & msg) const;
447
448         void setGuiDelegate(frontend::GuiBufferDelegate * gui);
449
450         ///
451         void autoSave() const;
452
453         /// return the format of the buffer on a string
454         std::string bufferFormat() const;
455
456         ///
457         bool doExport(std::string const & format, bool put_in_tempdir,
458                 std::string & result_file) const;
459         ///
460         bool doExport(std::string const & format, bool put_in_tempdir) const;
461         ///
462         bool preview(std::string const & format) const;
463         ///
464         bool isExportable(std::string const & format) const;
465         ///
466         std::vector<Format const *> exportableFormats(bool only_viewable) const;
467
468         ///
469         typedef std::vector<std::pair<InsetRef *, ParIterator> > References;
470         References & references(docstring const & label);
471         References const & references(docstring const & label) const;
472         void clearReferenceCache() const;
473         void setInsetLabel(docstring const & label, InsetLabel const * il);
474         InsetLabel const * insetLabel(docstring const & label) const;
475
476         // FIXME: buf should should be const because updateLabels() modifies
477         // the contents of the paragraphs.
478         void updateLabels(bool childonly = false) const;
479         ///
480         void updateLabels(ParIterator & parit) const;
481
482 private:
483         /// search for macro in local (buffer) table or in children
484         MacroData const * getBufferMacro(docstring const & name,
485                                          DocIterator const & pos) const;
486         /** Update macro table starting with position of it
487             \param it in some text inset
488         */
489         void updateMacros(DocIterator & it,
490                                      DocIterator & scope) const;
491
492         ///
493         void collectRelatives(BufferSet & bufs) const;
494
495         ///
496         bool readFileHelper(support::FileName const & s);
497         ///
498         std::vector<std::string> backends() const;
499         /** Inserts a file into a document
500             \return \c false if method fails.
501         */
502         ReadStatus readFile(Lexer &, support::FileName const & filename,
503                             bool fromString = false);
504
505         /// Use the Pimpl idiom to hide the internals.
506         class Impl;
507         /// The pointer never changes although *pimpl_'s contents may.
508         Impl * const d;
509
510         frontend::GuiBufferDelegate * gui_;
511
512         /// This function is called when the buffer structure is changed.
513         Signal structureChanged_;
514         /// This function is called when some parsing error shows up.
515         //Signal errors(std::string const &) = 0;
516         /// This function is called when some message shows up.
517         //Signal message(docstring const &) = 0;
518         /// This function is called when the buffer busy status change.
519         //Signal setBusy(bool) = 0;
520         /// Reset autosave timers for all users.
521         Signal resetAutosaveTimers_;
522 };
523
524
525 } // namespace lyx
526
527 #endif