| author | wenzelm | 
| Sun, 29 Dec 2024 13:16:26 +0100 | |
| changeset 81685 | 13bd6223691d | 
| parent 80225 | d9ff4296e3b7 | 
| permissions | -rw-r--r-- | 
| 79503 | 1 | /* Title: Pure/General/bibtex.scala | 
| 58523 | 2 | Author: Makarius | 
| 3 | ||
| 79503 | 4 | Support for BibTeX. | 
| 58523 | 5 | */ | 
| 6 | ||
| 7 | package isabelle | |
| 8 | ||
| 9 | ||
| 58528 | 10 | import scala.collection.mutable | 
| 58523 | 11 | import scala.util.parsing.combinator.RegexParsers | 
| 64824 | 12 | import scala.util.parsing.input.Reader | 
| 76972 | 13 | import scala.util.matching.Regex | 
| 58523 | 14 | |
| 77011 
3e48f8c6afc9
parse citations from raw source, without formal context;
 wenzelm parents: 
77010diff
changeset | 15 | import isabelle.{Token => Isar_Token}
 | 
| 
3e48f8c6afc9
parse citations from raw source, without formal context;
 wenzelm parents: 
77010diff
changeset | 16 | |
| 58523 | 17 | |
| 75393 | 18 | object Bibtex {
 | 
| 69255 
800b1ce96fce
more general support for Isabelle/PIDE file formats -- less hardwired Bibtex operations;
 wenzelm parents: 
68224diff
changeset | 19 | /** file format **/ | 
| 
800b1ce96fce
more general support for Isabelle/PIDE file formats -- less hardwired Bibtex operations;
 wenzelm parents: 
68224diff
changeset | 20 | |
| 75393 | 21 |   class File_Format extends isabelle.File_Format {
 | 
| 69255 
800b1ce96fce
more general support for Isabelle/PIDE file formats -- less hardwired Bibtex operations;
 wenzelm parents: 
68224diff
changeset | 22 | val format_name: String = "bibtex" | 
| 69257 | 23 | val file_ext: String = "bib" | 
| 69255 
800b1ce96fce
more general support for Isabelle/PIDE file formats -- less hardwired Bibtex operations;
 wenzelm parents: 
68224diff
changeset | 24 | |
| 76792 
23f433294173
support for generic File_Format.parse_data, with persistent result in document model;
 wenzelm parents: 
76779diff
changeset | 25 | override def parse_data(name: String, text: String): Bibtex.Entries = | 
| 77030 
d7dc5b1e4381
proper positions for Isabelle/ML, instead of Isabelle/Scala;
 wenzelm parents: 
77029diff
changeset | 26 | Bibtex.Entries.parse(text, Isar_Token.Pos.file(name)) | 
| 76792 
23f433294173
support for generic File_Format.parse_data, with persistent result in document model;
 wenzelm parents: 
76779diff
changeset | 27 | |
| 69257 | 28 | override def theory_suffix: String = "bibtex_file" | 
| 69259 | 29 | override def theory_content(name: String): String = | 
| 76859 | 30 | """theory "bib" imports Pure begin bibtex_file "." end""" | 
| 76849 
d431a9340163
more systematic Sessions.illegal_theory, based on File_Format.theory_excluded;
 wenzelm parents: 
76829diff
changeset | 31 | override def theory_excluded(name: String): Boolean = name == "bib" | 
| 69255 
800b1ce96fce
more general support for Isabelle/PIDE file formats -- less hardwired Bibtex operations;
 wenzelm parents: 
68224diff
changeset | 32 | |
| 75941 | 33 |     override def html_document(snapshot: Document.Snapshot): Option[Browser_Info.HTML_Document] = {
 | 
| 69255 
800b1ce96fce
more general support for Isabelle/PIDE file formats -- less hardwired Bibtex operations;
 wenzelm parents: 
68224diff
changeset | 34 | val name = snapshot.node_name | 
| 
800b1ce96fce
more general support for Isabelle/PIDE file formats -- less hardwired Bibtex operations;
 wenzelm parents: 
68224diff
changeset | 35 |       if (detect(name.node)) {
 | 
| 76829 
f2a8ba0b8c96
more robust: avoid detour via somewhat fragile Node.Name.path;
 wenzelm parents: 
76793diff
changeset | 36 | val title = "Bibliography " + quote(snapshot.node_name.file_name) | 
| 69255 
800b1ce96fce
more general support for Isabelle/PIDE file formats -- less hardwired Bibtex operations;
 wenzelm parents: 
68224diff
changeset | 37 | val content = | 
| 
800b1ce96fce
more general support for Isabelle/PIDE file formats -- less hardwired Bibtex operations;
 wenzelm parents: 
68224diff
changeset | 38 |           Isabelle_System.with_tmp_file("bib", "bib") { bib =>
 | 
| 76933 | 39 | File.write(bib, snapshot.node.source) | 
| 69255 
800b1ce96fce
more general support for Isabelle/PIDE file formats -- less hardwired Bibtex operations;
 wenzelm parents: 
68224diff
changeset | 40 | Bibtex.html_output(List(bib), style = "unsort", title = title) | 
| 
800b1ce96fce
more general support for Isabelle/PIDE file formats -- less hardwired Bibtex operations;
 wenzelm parents: 
68224diff
changeset | 41 | } | 
| 75941 | 42 | Some(Browser_Info.HTML_Document(title, content)) | 
| 69255 
800b1ce96fce
more general support for Isabelle/PIDE file formats -- less hardwired Bibtex operations;
 wenzelm parents: 
68224diff
changeset | 43 | } | 
| 
800b1ce96fce
more general support for Isabelle/PIDE file formats -- less hardwired Bibtex operations;
 wenzelm parents: 
68224diff
changeset | 44 | else None | 
| 
800b1ce96fce
more general support for Isabelle/PIDE file formats -- less hardwired Bibtex operations;
 wenzelm parents: 
68224diff
changeset | 45 | } | 
| 
800b1ce96fce
more general support for Isabelle/PIDE file formats -- less hardwired Bibtex operations;
 wenzelm parents: 
68224diff
changeset | 46 | } | 
| 
800b1ce96fce
more general support for Isabelle/PIDE file formats -- less hardwired Bibtex operations;
 wenzelm parents: 
68224diff
changeset | 47 | |
| 
800b1ce96fce
more general support for Isabelle/PIDE file formats -- less hardwired Bibtex operations;
 wenzelm parents: 
68224diff
changeset | 48 | |
| 
800b1ce96fce
more general support for Isabelle/PIDE file formats -- less hardwired Bibtex operations;
 wenzelm parents: 
68224diff
changeset | 49 | |
| 67203 | 50 | /** bibtex errors **/ | 
| 51 | ||
| 75393 | 52 |   def bibtex_errors(dir: Path, root_name: String): List[String] = {
 | 
| 77035 | 53 | val log_path = dir + Path.explode(root_name).blg | 
| 67203 | 54 |     if (log_path.is_file) {
 | 
| 67300 | 55 | val Error1 = """^(I couldn't open database file .+)$""".r | 
| 73730 
2f023b2b0e1e
more uniform bibtex error, without using perl (see 4710dd5093a3);
 wenzelm parents: 
73565diff
changeset | 56 | val Error2 = """^(I found no .+)$""".r | 
| 
2f023b2b0e1e
more uniform bibtex error, without using perl (see 4710dd5093a3);
 wenzelm parents: 
73565diff
changeset | 57 | val Error3 = """^(.+)---line (\d+) of file (.+)""".r | 
| 67203 | 58 | Line.logical_lines(File.read(log_path)).flatMap(line => | 
| 59 |         line match {
 | |
| 67300 | 60 |           case Error1(msg) => Some("Bibtex error: " + msg)
 | 
| 73730 
2f023b2b0e1e
more uniform bibtex error, without using perl (see 4710dd5093a3);
 wenzelm parents: 
73565diff
changeset | 61 |           case Error2(msg) => Some("Bibtex error: " + msg)
 | 
| 
2f023b2b0e1e
more uniform bibtex error, without using perl (see 4710dd5093a3);
 wenzelm parents: 
73565diff
changeset | 62 | case Error3(msg, Value.Int(l), file) => | 
| 67203 | 63 | val path = File.standard_path(file) | 
| 64 |             if (Path.is_wellformed(path)) {
 | |
| 65 | val pos = Position.Line_File(l, (dir + Path.explode(path)).canonical.implode) | |
| 66 |               Some("Bibtex error" + Position.here(pos) + ":\n  " + msg)
 | |
| 67 | } | |
| 68 | else None | |
| 69 | case _ => None | |
| 70 | }) | |
| 71 | } | |
| 72 | else Nil | |
| 73 | } | |
| 74 | ||
| 75 | ||
| 76 | ||
| 67272 | 77 | /** check database **/ | 
| 78 | ||
| 75393 | 79 |   def check_database(database: String): (List[(String, Position.T)], List[(String, Position.T)]) = {
 | 
| 67275 
5e427586cb57
check bibtex database on ML side -- for semantic PIDE editing;
 wenzelm parents: 
67274diff
changeset | 80 | val chunks = parse(Line.normalize(database)) | 
| 
5e427586cb57
check bibtex database on ML side -- for semantic PIDE editing;
 wenzelm parents: 
67274diff
changeset | 81 | var chunk_pos = Map.empty[String, Position.T] | 
| 67272 | 82 | val tokens = new mutable.ListBuffer[(Token, Position.T)] | 
| 83 | var line = 1 | |
| 84 | var offset = 1 | |
| 85 | ||
| 67276 | 86 | def make_pos(length: Int): Position.T = | 
| 87 | Position.Offset(offset) ::: Position.End_Offset(offset + length) ::: Position.Line(line) | |
| 67272 | 88 | |
| 75393 | 89 |     def advance_pos(tok: Token): Unit = {
 | 
| 67272 | 90 |       for (s <- Symbol.iterator(tok.source)) {
 | 
| 91 | if (Symbol.is_newline(s)) line += 1 | |
| 92 | offset += 1 | |
| 93 | } | |
| 94 | } | |
| 95 | ||
| 96 | def get_line_pos(l: Int): Position.T = | |
| 97 | if (0 < l && l <= tokens.length) tokens(l - 1)._2 else Position.none | |
| 98 | ||
| 99 |     for (chunk <- chunks) {
 | |
| 100 | val name = chunk.name | |
| 101 |       if (name != "" && !chunk_pos.isDefinedAt(name)) {
 | |
| 67276 | 102 | chunk_pos += (name -> make_pos(chunk.heading_length)) | 
| 67272 | 103 | } | 
| 104 |       for (tok <- chunk.tokens) {
 | |
| 67276 | 105 |         tokens += (tok.copy(source = tok.source.replace("\n", " ")) -> make_pos(tok.source.length))
 | 
| 67272 | 106 | advance_pos(tok) | 
| 107 | } | |
| 108 | } | |
| 109 | ||
| 75394 | 110 |     Isabelle_System.with_tmp_dir("bibtex") { tmp_dir =>
 | 
| 67272 | 111 |       File.write(tmp_dir + Path.explode("root.bib"),
 | 
| 112 |         tokens.iterator.map(p => p._1.source).mkString("", "\n", "\n"))
 | |
| 113 |       File.write(tmp_dir + Path.explode("root.aux"),
 | |
| 114 |         "\\bibstyle{plain}\n\\bibdata{root}\n\\citation{*}")
 | |
| 80224 
db92e0b6a11a
clarified signature: prefer symbolic isabelle.Path over physical java.io.File;
 wenzelm parents: 
79503diff
changeset | 115 |       Isabelle_System.bash("\"$ISABELLE_BIBTEX\" root", cwd = tmp_dir)
 | 
| 67272 | 116 | |
| 117 | val Error = """^(.*)---line (\d+) of file root.bib$""".r | |
| 118 | val Warning = """^Warning--(.+)$""".r | |
| 119 | val Warning_Line = """--line (\d+) of file root.bib$""".r | |
| 120 | val Warning_in_Chunk = """^Warning--(.+) in (.+)$""".r | |
| 121 | ||
| 122 |       val log_file = tmp_dir + Path.explode("root.blg")
 | |
| 123 | val lines = if (log_file.is_file) Line.logical_lines(File.read(log_file)) else Nil | |
| 124 | ||
| 67301 | 125 | val (errors, warnings) = | 
| 69294 | 126 | if (lines.isEmpty) (Nil, Nil) | 
| 127 |         else {
 | |
| 128 |           lines.zip(lines.tail ::: List("")).flatMap(
 | |
| 129 |             {
 | |
| 130 | case (Error(msg, Value.Int(l)), _) => | |
| 131 | Some((true, (msg, get_line_pos(l)))) | |
| 132 | case (Warning_in_Chunk(msg, name), _) if chunk_pos.isDefinedAt(name) => | |
| 78614 | 133 | Some((false, (Word.capitalized(msg) + " in entry " + quote(name), chunk_pos(name)))) | 
| 69294 | 134 | case (Warning(msg), Warning_Line(Value.Int(l))) => | 
| 78614 | 135 | Some((false, (Word.capitalized(msg), get_line_pos(l)))) | 
| 69294 | 136 | case (Warning(msg), _) => | 
| 78614 | 137 | Some((false, (Word.capitalized(msg), Position.none))) | 
| 69294 | 138 | case _ => None | 
| 139 | } | |
| 140 | ).partition(_._1) | |
| 141 | } | |
| 67301 | 142 | (errors.map(_._2), warnings.map(_._2)) | 
| 75394 | 143 | } | 
| 67272 | 144 | } | 
| 145 | ||
| 75393 | 146 |   object Check_Database extends Scala.Fun_String("bibtex_check_database") {
 | 
| 72756 | 147 | val here = Scala_Project.here | 
| 75393 | 148 |     def apply(database: String): String = {
 | 
| 72193 | 149 | import XML.Encode._ | 
| 150 | YXML.string_of_body(pair(list(pair(string, properties)), list(pair(string, properties)))( | |
| 151 | check_database(database))) | |
| 152 | } | |
| 67275 
5e427586cb57
check bibtex database on ML side -- for semantic PIDE editing;
 wenzelm parents: 
67274diff
changeset | 153 | } | 
| 
5e427586cb57
check bibtex database on ML side -- for semantic PIDE editing;
 wenzelm parents: 
67274diff
changeset | 154 | |
| 67272 | 155 | |
| 156 | ||
| 64828 | 157 | /** document model **/ | 
| 158 | ||
| 67290 | 159 | /* entries */ | 
| 64828 | 160 | |
| 77032 | 161 |   sealed case class Entry(name: String, pos: Position.T) {
 | 
| 162 | def encode: String = YXML.string_of_body(XML.Encode.properties(Markup.Name(name) ::: pos)) | |
| 163 | } | |
| 164 | ||
| 76776 | 165 |   object Entries {
 | 
| 166 | val empty: Entries = apply(Nil) | |
| 167 | ||
| 77032 | 168 | def apply(entries: List[Entry], errors: List[String] = Nil): Entries = | 
| 76778 
4086a0e4723b
clarified signature: internalize errors (but: the parser rarely fails);
 wenzelm parents: 
76776diff
changeset | 169 | new Entries(entries, errors) | 
| 76776 | 170 | |
| 77030 
d7dc5b1e4381
proper positions for Isabelle/ML, instead of Isabelle/Scala;
 wenzelm parents: 
77029diff
changeset | 171 |     def parse(text: String, start: Isar_Token.Pos = Isar_Token.Pos.start): Entries = {
 | 
| 77032 | 172 | val entries = new mutable.ListBuffer[Entry] | 
| 77030 
d7dc5b1e4381
proper positions for Isabelle/ML, instead of Isabelle/Scala;
 wenzelm parents: 
77029diff
changeset | 173 | var pos = start | 
| 76779 | 174 | var err_line = 0 | 
| 76778 
4086a0e4723b
clarified signature: internalize errors (but: the parser rarely fails);
 wenzelm parents: 
76776diff
changeset | 175 | |
| 
4086a0e4723b
clarified signature: internalize errors (but: the parser rarely fails);
 wenzelm parents: 
76776diff
changeset | 176 |       try {
 | 
| 
4086a0e4723b
clarified signature: internalize errors (but: the parser rarely fails);
 wenzelm parents: 
76776diff
changeset | 177 |         for (chunk <- Bibtex.parse(text)) {
 | 
| 77030 
d7dc5b1e4381
proper positions for Isabelle/ML, instead of Isabelle/Scala;
 wenzelm parents: 
77029diff
changeset | 178 | val pos1 = pos.advance(chunk.source) | 
| 76778 
4086a0e4723b
clarified signature: internalize errors (but: the parser rarely fails);
 wenzelm parents: 
76776diff
changeset | 179 |           if (chunk.name != "" && !chunk.is_command) {
 | 
| 77032 | 180 | entries += Entry(chunk.name, pos.position(pos1.offset)) | 
| 76778 
4086a0e4723b
clarified signature: internalize errors (but: the parser rarely fails);
 wenzelm parents: 
76776diff
changeset | 181 | } | 
| 77030 
d7dc5b1e4381
proper positions for Isabelle/ML, instead of Isabelle/Scala;
 wenzelm parents: 
77029diff
changeset | 182 |           if (chunk.is_malformed && err_line == 0) { err_line = pos.line }
 | 
| 
d7dc5b1e4381
proper positions for Isabelle/ML, instead of Isabelle/Scala;
 wenzelm parents: 
77029diff
changeset | 183 | pos = pos1 | 
| 76778 
4086a0e4723b
clarified signature: internalize errors (but: the parser rarely fails);
 wenzelm parents: 
76776diff
changeset | 184 | } | 
| 76779 | 185 | |
| 186 | val err_pos = | |
| 77030 
d7dc5b1e4381
proper positions for Isabelle/ML, instead of Isabelle/Scala;
 wenzelm parents: 
77029diff
changeset | 187 | if (err_line == 0 || pos.file.isEmpty) Position.none | 
| 
d7dc5b1e4381
proper positions for Isabelle/ML, instead of Isabelle/Scala;
 wenzelm parents: 
77029diff
changeset | 188 | else Position.Line_File(err_line, pos.file) | 
| 76779 | 189 | val errors = | 
| 190 | if (err_line == 0) Nil | |
| 191 |           else List("Malformed bibtex file" + Position.here(err_pos))
 | |
| 192 | ||
| 193 | apply(entries.toList, errors = errors) | |
| 76776 | 194 | } | 
| 76778 
4086a0e4723b
clarified signature: internalize errors (but: the parser rarely fails);
 wenzelm parents: 
76776diff
changeset | 195 |       catch { case ERROR(msg) => apply(Nil, errors = List(msg)) }
 | 
| 64828 | 196 | } | 
| 197 | } | |
| 198 | ||
| 77032 | 199 |   final class Entries private(val entries: List[Entry], val errors: List[String]) {
 | 
| 76793 | 200 |     override def toString: String = "Bibtex.Entries(" + entries.length + ")"
 | 
| 201 | ||
| 76778 
4086a0e4723b
clarified signature: internalize errors (but: the parser rarely fails);
 wenzelm parents: 
76776diff
changeset | 202 | def ::: (other: Entries): Entries = | 
| 77219 
a10161fbc6de
proper orientation for right-associative operations;
 wenzelm parents: 
77218diff
changeset | 203 | new Entries(other.entries ::: entries, other.errors ::: errors) | 
| 66150 | 204 | } | 
| 205 | ||
| 77028 
f5896dea6fce
more direct check of bibtex entries via Isabelle/Scala;
 wenzelm parents: 
77025diff
changeset | 206 |   object Session_Entries extends Scala.Fun("bibtex_session_entries") {
 | 
| 
f5896dea6fce
more direct check of bibtex entries via Isabelle/Scala;
 wenzelm parents: 
77025diff
changeset | 207 | val here = Scala_Project.here | 
| 
f5896dea6fce
more direct check of bibtex entries via Isabelle/Scala;
 wenzelm parents: 
77025diff
changeset | 208 | |
| 
f5896dea6fce
more direct check of bibtex entries via Isabelle/Scala;
 wenzelm parents: 
77025diff
changeset | 209 |     override def invoke(session: Session, args: List[Bytes]): List[Bytes] = {
 | 
| 
f5896dea6fce
more direct check of bibtex entries via Isabelle/Scala;
 wenzelm parents: 
77025diff
changeset | 210 | val sessions = session.resources.sessions_structure | 
| 
f5896dea6fce
more direct check of bibtex entries via Isabelle/Scala;
 wenzelm parents: 
77025diff
changeset | 211 | val id = Value.Long.parse(Library.the_single(args).text) | 
| 
f5896dea6fce
more direct check of bibtex entries via Isabelle/Scala;
 wenzelm parents: 
77025diff
changeset | 212 | val qualifier = | 
| 
f5896dea6fce
more direct check of bibtex entries via Isabelle/Scala;
 wenzelm parents: 
77025diff
changeset | 213 |         session.get_state().lookup_id(id) match {
 | 
| 
f5896dea6fce
more direct check of bibtex entries via Isabelle/Scala;
 wenzelm parents: 
77025diff
changeset | 214 | case None => Sessions.DRAFT | 
| 
f5896dea6fce
more direct check of bibtex entries via Isabelle/Scala;
 wenzelm parents: 
77025diff
changeset | 215 | case Some(st) => sessions.theory_qualifier(st.command.node_name.theory) | 
| 
f5896dea6fce
more direct check of bibtex entries via Isabelle/Scala;
 wenzelm parents: 
77025diff
changeset | 216 | } | 
| 
f5896dea6fce
more direct check of bibtex entries via Isabelle/Scala;
 wenzelm parents: 
77025diff
changeset | 217 | val res = | 
| 
f5896dea6fce
more direct check of bibtex entries via Isabelle/Scala;
 wenzelm parents: 
77025diff
changeset | 218 | if (qualifier == Sessions.DRAFT || !sessions.defined(qualifier)) Nil | 
| 77030 
d7dc5b1e4381
proper positions for Isabelle/ML, instead of Isabelle/Scala;
 wenzelm parents: 
77029diff
changeset | 219 | else qualifier :: sessions(qualifier).bibtex_entries.entries.map(_.encode) | 
| 77028 
f5896dea6fce
more direct check of bibtex entries via Isabelle/Scala;
 wenzelm parents: 
77025diff
changeset | 220 | res.map(Bytes.apply) | 
| 
f5896dea6fce
more direct check of bibtex entries via Isabelle/Scala;
 wenzelm parents: 
77025diff
changeset | 221 | } | 
| 
f5896dea6fce
more direct check of bibtex entries via Isabelle/Scala;
 wenzelm parents: 
77025diff
changeset | 222 | } | 
| 
f5896dea6fce
more direct check of bibtex entries via Isabelle/Scala;
 wenzelm parents: 
77025diff
changeset | 223 | |
| 64828 | 224 | |
| 225 | ||
| 58523 | 226 | /** content **/ | 
| 227 | ||
| 58529 | 228 | private val months = List( | 
| 58523 | 229 | "jan", | 
| 230 | "feb", | |
| 231 | "mar", | |
| 232 | "apr", | |
| 233 | "may", | |
| 234 | "jun", | |
| 235 | "jul", | |
| 236 | "aug", | |
| 237 | "sep", | |
| 238 | "oct", | |
| 239 | "nov", | |
| 240 | "dec") | |
| 58529 | 241 | def is_month(s: String): Boolean = months.contains(s.toLowerCase) | 
| 58523 | 242 | |
| 58529 | 243 |   private val commands = List("preamble", "string")
 | 
| 244 | def is_command(s: String): Boolean = commands.contains(s.toLowerCase) | |
| 58523 | 245 | |
| 77031 | 246 | sealed case class Entry_Type( | 
| 58526 | 247 | kind: String, | 
| 58523 | 248 | required: List[String], | 
| 249 | optional_crossref: List[String], | |
| 75393 | 250 | optional_other: List[String] | 
| 251 |   ) {
 | |
| 70230 | 252 |     val optional_standard: List[String] = List("url", "doi", "ee")
 | 
| 253 | ||
| 58533 | 254 | def is_required(s: String): Boolean = required.contains(s.toLowerCase) | 
| 58529 | 255 | def is_optional(s: String): Boolean = | 
| 70230 | 256 | optional_crossref.contains(s.toLowerCase) || | 
| 257 | optional_other.contains(s.toLowerCase) || | |
| 258 | optional_standard.contains(s.toLowerCase) | |
| 58529 | 259 | |
| 70230 | 260 | def fields: List[String] = | 
| 261 | required ::: optional_crossref ::: optional_other ::: optional_standard | |
| 262 | ||
| 58524 | 263 | def template: String = | 
| 58526 | 264 |       "@" + kind + "{,\n" + fields.map(x => "  " + x + " = {},\n").mkString + "}\n"
 | 
| 58524 | 265 | } | 
| 58523 | 266 | |
| 77031 | 267 | val known_entries: List[Entry_Type] = | 
| 58524 | 268 | List( | 
| 77031 | 269 |       Entry_Type("Article",
 | 
| 58524 | 270 |         List("author", "title"),
 | 
| 271 |         List("journal", "year"),
 | |
| 272 |         List("volume", "number", "pages", "month", "note")),
 | |
| 77031 | 273 |       Entry_Type("InProceedings",
 | 
| 58524 | 274 |         List("author", "title"),
 | 
| 275 |         List("booktitle", "year"),
 | |
| 276 |         List("editor", "volume", "number", "series", "pages", "month", "address",
 | |
| 277 | "organization", "publisher", "note")), | |
| 77031 | 278 |       Entry_Type("InCollection",
 | 
| 58524 | 279 |         List("author", "title", "booktitle"),
 | 
| 280 |         List("publisher", "year"),
 | |
| 281 |         List("editor", "volume", "number", "series", "type", "chapter", "pages",
 | |
| 282 | "edition", "month", "address", "note")), | |
| 77031 | 283 |       Entry_Type("InBook",
 | 
| 58524 | 284 |         List("author", "editor", "title", "chapter"),
 | 
| 285 |         List("publisher", "year"),
 | |
| 286 |         List("volume", "number", "series", "type", "address", "edition", "month", "pages", "note")),
 | |
| 77031 | 287 |       Entry_Type("Proceedings",
 | 
| 58524 | 288 |         List("title", "year"),
 | 
| 289 | List(), | |
| 290 |         List("booktitle", "editor", "volume", "number", "series", "address", "month",
 | |
| 291 | "organization", "publisher", "note")), | |
| 77031 | 292 |       Entry_Type("Book",
 | 
| 58524 | 293 |         List("author", "editor", "title"),
 | 
| 294 |         List("publisher", "year"),
 | |
| 295 |         List("volume", "number", "series", "address", "edition", "month", "note")),
 | |
| 77031 | 296 |       Entry_Type("Booklet",
 | 
| 58524 | 297 |         List("title"),
 | 
| 298 | List(), | |
| 299 |         List("author", "howpublished", "address", "month", "year", "note")),
 | |
| 77031 | 300 |       Entry_Type("PhdThesis",
 | 
| 58524 | 301 |         List("author", "title", "school", "year"),
 | 
| 302 | List(), | |
| 303 |         List("type", "address", "month", "note")),
 | |
| 77031 | 304 |       Entry_Type("MastersThesis",
 | 
| 58524 | 305 |         List("author", "title", "school", "year"),
 | 
| 306 | List(), | |
| 307 |         List("type", "address", "month", "note")),
 | |
| 77031 | 308 |       Entry_Type("TechReport",
 | 
| 58524 | 309 |         List("author", "title", "institution", "year"),
 | 
| 310 | List(), | |
| 311 |         List("type", "number", "address", "month", "note")),
 | |
| 77031 | 312 |       Entry_Type("Manual",
 | 
| 58524 | 313 |         List("title"),
 | 
| 314 | List(), | |
| 315 |         List("author", "organization", "address", "edition", "month", "year", "note")),
 | |
| 77031 | 316 |       Entry_Type("Unpublished",
 | 
| 58524 | 317 |         List("author", "title", "note"),
 | 
| 318 | List(), | |
| 319 |         List("month", "year")),
 | |
| 77031 | 320 |       Entry_Type("Misc",
 | 
| 58524 | 321 | List(), | 
| 322 | List(), | |
| 323 |         List("author", "title", "howpublished", "month", "year", "note")))
 | |
| 58523 | 324 | |
| 77031 | 325 | def known_entry(kind: String): Option[Entry_Type] = | 
| 66150 | 326 | known_entries.find(entry => entry.kind.toLowerCase == kind.toLowerCase) | 
| 58529 | 327 | |
| 58523 | 328 | |
| 329 | ||
| 330 | /** tokens and chunks **/ | |
| 331 | ||
| 75393 | 332 |   object Token {
 | 
| 333 |     object Kind extends Enumeration {
 | |
| 58529 | 334 |       val COMMAND = Value("command")
 | 
| 335 |       val ENTRY = Value("entry")
 | |
| 58523 | 336 |       val KEYWORD = Value("keyword")
 | 
| 337 |       val NAT = Value("natural number")
 | |
| 58529 | 338 |       val STRING = Value("string")
 | 
| 58531 | 339 |       val NAME = Value("name")
 | 
| 58523 | 340 |       val IDENT = Value("identifier")
 | 
| 58535 | 341 |       val SPACE = Value("white space")
 | 
| 342 |       val COMMENT = Value("ignored text")
 | |
| 58523 | 343 |       val ERROR = Value("bad input")
 | 
| 344 | } | |
| 345 | } | |
| 346 | ||
| 75393 | 347 |   sealed case class Token(kind: Token.Kind.Value, source: String) {
 | 
| 58530 | 348 | def is_kind: Boolean = | 
| 349 | kind == Token.Kind.COMMAND || | |
| 350 | kind == Token.Kind.ENTRY || | |
| 351 | kind == Token.Kind.IDENT | |
| 58531 | 352 | def is_name: Boolean = | 
| 353 | kind == Token.Kind.NAME || | |
| 354 | kind == Token.Kind.IDENT | |
| 58535 | 355 | def is_ignored: Boolean = | 
| 356 | kind == Token.Kind.SPACE || | |
| 357 | kind == Token.Kind.COMMENT | |
| 67276 | 358 | def is_malformed: Boolean = | 
| 359 | kind == Token.Kind.ERROR | |
| 360 | def is_open: Boolean = | |
| 361 |       kind == Token.Kind.KEYWORD && (source == "{" || source == "(")
 | |
| 58523 | 362 | } | 
| 363 | ||
| 75393 | 364 |   case class Chunk(kind: String, tokens: List[Token]) {
 | 
| 77010 
fead2b33acdc
tuned signature: fewer warnings in IntelliJ IDEA;
 wenzelm parents: 
77007diff
changeset | 365 | val source: String = tokens.map(_.source).mkString | 
| 58526 | 366 | |
| 58530 | 367 | private val content: Option[List[Token]] = | 
| 58523 | 368 |       tokens match {
 | 
| 59319 | 369 | case Token(Token.Kind.KEYWORD, "@") :: body if body.nonEmpty => | 
| 58529 | 370 |           (body.init.filterNot(_.is_ignored), body.last) match {
 | 
| 58530 | 371 |             case (tok :: Token(Token.Kind.KEYWORD, "{") :: toks, Token(Token.Kind.KEYWORD, "}"))
 | 
| 372 | if tok.is_kind => Some(toks) | |
| 373 | ||
| 374 |             case (tok :: Token(Token.Kind.KEYWORD, "(") :: toks, Token(Token.Kind.KEYWORD, ")"))
 | |
| 375 | if tok.is_kind => Some(toks) | |
| 376 | ||
| 58528 | 377 | case _ => None | 
| 58523 | 378 | } | 
| 58528 | 379 | case _ => None | 
| 58526 | 380 | } | 
| 381 | ||
| 382 | def name: String = | |
| 58530 | 383 |       content match {
 | 
| 58531 | 384 | case Some(tok :: _) if tok.is_name => tok.source | 
| 58523 | 385 | case _ => "" | 
| 386 | } | |
| 58530 | 387 | |
| 67276 | 388 | def heading_length: Int = | 
| 389 | if (name == "") 1 | |
| 73359 | 390 |       else {
 | 
| 391 |         tokens.takeWhile(tok => !tok.is_open).foldLeft(0) { case (n, tok) => n + tok.source.length }
 | |
| 392 | } | |
| 67276 | 393 | |
| 58530 | 394 | def is_ignored: Boolean = kind == "" && tokens.forall(_.is_ignored) | 
| 76779 | 395 | def is_malformed: Boolean = tokens.exists(_.is_malformed) | 
| 58543 | 396 | def is_command: Boolean = Bibtex.is_command(kind) && name != "" && content.isDefined | 
| 77031 | 397 | def is_entry: Boolean = Bibtex.known_entry(kind).isDefined && name != "" && content.isDefined | 
| 58523 | 398 | } | 
| 399 | ||
| 400 | ||
| 401 | ||
| 402 | /** parsing **/ | |
| 403 | ||
| 404 | // context of partial line-oriented scans | |
| 405 | abstract class Line_Context | |
| 58589 | 406 | case object Ignored extends Line_Context | 
| 58590 
472b9fbcc7f0
back to liberal spaces of official syntax (in contrast to 4b190c763097), e.g. relevant for easychair.bib;
 wenzelm parents: 
58589diff
changeset | 407 | case object At extends Line_Context | 
| 
472b9fbcc7f0
back to liberal spaces of official syntax (in contrast to 4b190c763097), e.g. relevant for easychair.bib;
 wenzelm parents: 
58589diff
changeset | 408 | case class Item_Start(kind: String) extends Line_Context | 
| 58591 | 409 | case class Item_Open(kind: String, end: String) extends Line_Context | 
| 410 | case class Item(kind: String, end: String, delim: Delimited) extends Line_Context | |
| 58590 
472b9fbcc7f0
back to liberal spaces of official syntax (in contrast to 4b190c763097), e.g. relevant for easychair.bib;
 wenzelm parents: 
58589diff
changeset | 411 | |
| 58528 | 412 | case class Delimited(quoted: Boolean, depth: Int) | 
| 77010 
fead2b33acdc
tuned signature: fewer warnings in IntelliJ IDEA;
 wenzelm parents: 
77007diff
changeset | 413 | val Closed: Delimited = Delimited(false, 0) | 
| 58523 | 414 | |
| 415 | private def token(kind: Token.Kind.Value)(source: String): Token = Token(kind, source) | |
| 416 | private def keyword(source: String): Token = Token(Token.Kind.KEYWORD, source) | |
| 417 | ||
| 418 | ||
| 68224 | 419 | // See also https://ctan.org/tex-archive/biblio/bibtex/base/bibtex.web | 
| 58523 | 420 |   // module @<Scan for and process a \.{.bib} command or database entry@>.
 | 
| 421 | ||
| 75393 | 422 |   object Parsers extends RegexParsers {
 | 
| 58523 | 423 | /* white space and comments */ | 
| 424 | ||
| 425 | override val whiteSpace = "".r | |
| 426 | ||
| 58535 | 427 | private val space = """[ \t\n\r]+""".r ^^ token(Token.Kind.SPACE) | 
| 58590 
472b9fbcc7f0
back to liberal spaces of official syntax (in contrast to 4b190c763097), e.g. relevant for easychair.bib;
 wenzelm parents: 
58589diff
changeset | 428 | private val spaces = rep(space) | 
| 58523 | 429 | |
| 58528 | 430 | |
| 58535 | 431 | /* ignored text */ | 
| 58528 | 432 | |
| 433 | private val ignored: Parser[Chunk] = | |
| 58609 | 434 |       rep1("""(?i)([^@]+|@[ \t]*comment)""".r) ^^ {
 | 
| 58535 | 435 |         case ss => Chunk("", List(Token(Token.Kind.COMMENT, ss.mkString))) }
 | 
| 58523 | 436 | |
| 58536 
402a8e8107a7
more total chunk_line: recovery via ignored_line;
 wenzelm parents: 
58535diff
changeset | 437 | private def ignored_line: Parser[(Chunk, Line_Context)] = | 
| 58589 | 438 |       ignored ^^ { case a => (a, Ignored) }
 | 
| 58536 
402a8e8107a7
more total chunk_line: recovery via ignored_line;
 wenzelm parents: 
58535diff
changeset | 439 | |
| 58523 | 440 | |
| 441 |     /* delimited string: outermost "..." or {...} and body with balanced {...} */
 | |
| 442 | ||
| 58534 | 443 | // see also bibtex.web: scan_a_field_token_and_eat_white, scan_balanced_braces | 
| 58523 | 444 | private def delimited_depth(delim: Delimited): Parser[(String, Delimited)] = | 
| 75393 | 445 |       new Parser[(String, Delimited)] {
 | 
| 73120 
c3589f2dff31
more informative errors: simplify diagnosis of spurious failures reported by users;
 wenzelm parents: 
72957diff
changeset | 446 | require(if (delim.quoted) delim.depth > 0 else delim.depth >= 0, | 
| 
c3589f2dff31
more informative errors: simplify diagnosis of spurious failures reported by users;
 wenzelm parents: 
72957diff
changeset | 447 | "bad delimiter depth") | 
| 58523 | 448 | |
| 77010 
fead2b33acdc
tuned signature: fewer warnings in IntelliJ IDEA;
 wenzelm parents: 
77007diff
changeset | 449 |         def apply(in: Input): ParseResult[(String, Delimited)] = {
 | 
| 58523 | 450 | val start = in.offset | 
| 451 | val end = in.source.length | |
| 452 | ||
| 453 | var i = start | |
| 454 | var q = delim.quoted | |
| 455 | var d = delim.depth | |
| 456 | var finished = false | |
| 457 |           while (!finished && i < end) {
 | |
| 458 | val c = in.source.charAt(i) | |
| 58534 | 459 | |
| 58523 | 460 |             if (c == '"' && d == 0) { i += 1; d = 1; q = true }
 | 
| 58532 | 461 |             else if (c == '"' && d == 1 && q) {
 | 
| 462 | i += 1; d = 0; q = false; finished = true | |
| 463 | } | |
| 58523 | 464 |             else if (c == '{') { i += 1; d += 1 }
 | 
| 58534 | 465 |             else if (c == '}') {
 | 
| 466 |               if (d == 1 && !q || d > 1) { i += 1; d -= 1; if (d == 0) finished = true }
 | |
| 467 |               else {i = start; finished = true }
 | |
| 58532 | 468 | } | 
| 58523 | 469 | else if (d > 0) i += 1 | 
| 470 | else finished = true | |
| 471 | } | |
| 472 |           if (i == start) Failure("bad input", in)
 | |
| 58528 | 473 |           else {
 | 
| 474 | val s = in.source.subSequence(start, i).toString | |
| 475 | Success((s, Delimited(q, d)), in.drop(i - start)) | |
| 476 | } | |
| 58523 | 477 | } | 
| 478 |       }.named("delimited_depth")
 | |
| 479 | ||
| 58528 | 480 | private def delimited: Parser[Token] = | 
| 481 | delimited_depth(Closed) ^? | |
| 482 |         { case (s, delim) if delim == Closed => Token(Token.Kind.STRING, s) }
 | |
| 58523 | 483 | |
| 58534 | 484 | private def recover_delimited: Parser[Token] = | 
| 58609 | 485 |       """["{][^@]*""".r ^^ token(Token.Kind.ERROR)
 | 
| 58534 | 486 | |
| 58590 
472b9fbcc7f0
back to liberal spaces of official syntax (in contrast to 4b190c763097), e.g. relevant for easychair.bib;
 wenzelm parents: 
58589diff
changeset | 487 | def delimited_line(ctxt: Item): Parser[(Chunk, Line_Context)] = | 
| 
472b9fbcc7f0
back to liberal spaces of official syntax (in contrast to 4b190c763097), e.g. relevant for easychair.bib;
 wenzelm parents: 
58589diff
changeset | 488 |       delimited_depth(ctxt.delim) ^^ { case (s, delim1) =>
 | 
| 
472b9fbcc7f0
back to liberal spaces of official syntax (in contrast to 4b190c763097), e.g. relevant for easychair.bib;
 wenzelm parents: 
58589diff
changeset | 489 | (Chunk(ctxt.kind, List(Token(Token.Kind.STRING, s))), ctxt.copy(delim = delim1)) } | | 
| 
472b9fbcc7f0
back to liberal spaces of official syntax (in contrast to 4b190c763097), e.g. relevant for easychair.bib;
 wenzelm parents: 
58589diff
changeset | 490 |       recover_delimited ^^ { case a => (Chunk(ctxt.kind, List(a)), Ignored) }
 | 
| 58523 | 491 | |
| 492 | ||
| 493 | /* other tokens */ | |
| 494 | ||
| 495 | private val at = "@" ^^ keyword | |
| 496 | ||
| 497 | private val nat = "[0-9]+".r ^^ token(Token.Kind.NAT) | |
| 498 | ||
| 58591 | 499 |     private val name = """[\x21-\x7f&&[^"#%'(),={}]]+""".r ^^ token(Token.Kind.NAME)
 | 
| 500 | ||
| 58529 | 501 | private val identifier = | 
| 502 |       """[\x21-\x7f&&[^"#%'(),={}0-9]][\x21-\x7f&&[^"#%'(),={}]]*""".r
 | |
| 503 | ||
| 504 | private val ident = identifier ^^ token(Token.Kind.IDENT) | |
| 58523 | 505 | |
| 77010 
fead2b33acdc
tuned signature: fewer warnings in IntelliJ IDEA;
 wenzelm parents: 
77007diff
changeset | 506 | val other_token: Parser[Token] = "[=#,]".r ^^ keyword | (nat | (ident | space)) | 
| 58528 | 507 | |
| 508 | ||
| 58591 | 509 | /* body */ | 
| 510 | ||
| 511 | private val body = | |
| 512 | delimited | (recover_delimited | other_token) | |
| 513 | ||
| 514 | private def body_line(ctxt: Item) = | |
| 515 | if (ctxt.delim.depth > 0) | |
| 516 | delimited_line(ctxt) | |
| 517 | else | |
| 518 | delimited_line(ctxt) | | |
| 519 |         other_token ^^ { case a => (Chunk(ctxt.kind, List(a)), ctxt) } |
 | |
| 520 |         ctxt.end ^^ { case a => (Chunk(ctxt.kind, List(keyword(a))), Ignored) }
 | |
| 521 | ||
| 522 | ||
| 58530 | 523 | /* items: command or entry */ | 
| 58528 | 524 | |
| 58530 | 525 | private val item_kind = | 
| 58529 | 526 |       identifier ^^ { case a =>
 | 
| 527 | val kind = | |
| 528 | if (is_command(a)) Token.Kind.COMMAND | |
| 77031 | 529 | else if (known_entry(a).isDefined) Token.Kind.ENTRY | 
| 58529 | 530 | else Token.Kind.IDENT | 
| 531 | Token(kind, a) | |
| 532 | } | |
| 533 | ||
| 58591 | 534 | private val item_begin = | 
| 535 |       "{" ^^ { case a => ("}", keyword(a)) } |
 | |
| 536 |       "(" ^^ { case a => (")", keyword(a)) }
 | |
| 537 | ||
| 538 | private def item_name(kind: String) = | |
| 539 |       kind.toLowerCase match {
 | |
| 540 |         case "preamble" => failure("")
 | |
| 541 | case "string" => identifier ^^ token(Token.Kind.NAME) | |
| 542 | case _ => name | |
| 543 | } | |
| 544 | ||
| 58531 | 545 | private val item_start = | 
| 58590 
472b9fbcc7f0
back to liberal spaces of official syntax (in contrast to 4b190c763097), e.g. relevant for easychair.bib;
 wenzelm parents: 
58589diff
changeset | 546 | at ~ spaces ~ item_kind ~ spaces ^^ | 
| 58528 | 547 |         { case a ~ b ~ c ~ d => (c.source, List(a) ::: b ::: List(c) ::: d) }
 | 
| 548 | ||
| 58530 | 549 | private val item: Parser[Chunk] = | 
| 58591 | 550 | (item_start ~ item_begin ~ spaces) into | 
| 551 |         { case (kind, a) ~ ((end, b)) ~ c =>
 | |
| 552 |             opt(item_name(kind)) ~ rep(body) ~ opt(end ^^ keyword) ^^ {
 | |
| 553 | case d ~ e ~ f => Chunk(kind, a ::: List(b) ::: c ::: d.toList ::: e ::: f.toList) } } | |
| 58528 | 554 | |
| 58530 | 555 | private val recover_item: Parser[Chunk] = | 
| 58609 | 556 |       at ~ "[^@]*".r ^^ { case a ~ b => Chunk("", List(a, Token(Token.Kind.ERROR, b))) }
 | 
| 58528 | 557 | |
| 58591 | 558 | |
| 559 | /* chunks */ | |
| 58523 | 560 | |
| 58528 | 561 | val chunk: Parser[Chunk] = ignored | (item | recover_item) | 
| 58523 | 562 | |
| 75393 | 563 |     def chunk_line(ctxt: Line_Context): Parser[(Chunk, Line_Context)] = {
 | 
| 58530 | 564 |       ctxt match {
 | 
| 58589 | 565 | case Ignored => | 
| 58538 
299b82d12d53
proper treatment of @comment (amending 402a8e8107a7);
 wenzelm parents: 
58536diff
changeset | 566 | ignored_line | | 
| 58590 
472b9fbcc7f0
back to liberal spaces of official syntax (in contrast to 4b190c763097), e.g. relevant for easychair.bib;
 wenzelm parents: 
58589diff
changeset | 567 |           at ^^ { case a => (Chunk("", List(a)), At) }
 | 
| 
472b9fbcc7f0
back to liberal spaces of official syntax (in contrast to 4b190c763097), e.g. relevant for easychair.bib;
 wenzelm parents: 
58589diff
changeset | 568 | |
| 
472b9fbcc7f0
back to liberal spaces of official syntax (in contrast to 4b190c763097), e.g. relevant for easychair.bib;
 wenzelm parents: 
58589diff
changeset | 569 | case At => | 
| 
472b9fbcc7f0
back to liberal spaces of official syntax (in contrast to 4b190c763097), e.g. relevant for easychair.bib;
 wenzelm parents: 
58589diff
changeset | 570 |           space ^^ { case a => (Chunk("", List(a)), ctxt) } |
 | 
| 
472b9fbcc7f0
back to liberal spaces of official syntax (in contrast to 4b190c763097), e.g. relevant for easychair.bib;
 wenzelm parents: 
58589diff
changeset | 571 |           item_kind ^^ { case a => (Chunk(a.source, List(a)), Item_Start(a.source)) } |
 | 
| 
472b9fbcc7f0
back to liberal spaces of official syntax (in contrast to 4b190c763097), e.g. relevant for easychair.bib;
 wenzelm parents: 
58589diff
changeset | 572 |           recover_item ^^ { case a => (a, Ignored) } |
 | 
| 
472b9fbcc7f0
back to liberal spaces of official syntax (in contrast to 4b190c763097), e.g. relevant for easychair.bib;
 wenzelm parents: 
58589diff
changeset | 573 | ignored_line | 
| 
472b9fbcc7f0
back to liberal spaces of official syntax (in contrast to 4b190c763097), e.g. relevant for easychair.bib;
 wenzelm parents: 
58589diff
changeset | 574 | |
| 
472b9fbcc7f0
back to liberal spaces of official syntax (in contrast to 4b190c763097), e.g. relevant for easychair.bib;
 wenzelm parents: 
58589diff
changeset | 575 | case Item_Start(kind) => | 
| 
472b9fbcc7f0
back to liberal spaces of official syntax (in contrast to 4b190c763097), e.g. relevant for easychair.bib;
 wenzelm parents: 
58589diff
changeset | 576 |           space ^^ { case a => (Chunk(kind, List(a)), ctxt) } |
 | 
| 58591 | 577 |           item_begin ^^ { case (end, a) => (Chunk(kind, List(a)), Item_Open(kind, end)) } |
 | 
| 58596 | 578 |           recover_item ^^ { case a => (a, Ignored) } |
 | 
| 58590 
472b9fbcc7f0
back to liberal spaces of official syntax (in contrast to 4b190c763097), e.g. relevant for easychair.bib;
 wenzelm parents: 
58589diff
changeset | 579 | ignored_line | 
| 
472b9fbcc7f0
back to liberal spaces of official syntax (in contrast to 4b190c763097), e.g. relevant for easychair.bib;
 wenzelm parents: 
58589diff
changeset | 580 | |
| 58591 | 581 | case Item_Open(kind, end) => | 
| 58590 
472b9fbcc7f0
back to liberal spaces of official syntax (in contrast to 4b190c763097), e.g. relevant for easychair.bib;
 wenzelm parents: 
58589diff
changeset | 582 |           space ^^ { case a => (Chunk(kind, List(a)), ctxt) } |
 | 
| 58591 | 583 |           item_name(kind) ^^ { case a => (Chunk(kind, List(a)), Item(kind, end, Closed)) } |
 | 
| 584 | body_line(Item(kind, end, Closed)) | | |
| 58590 
472b9fbcc7f0
back to liberal spaces of official syntax (in contrast to 4b190c763097), e.g. relevant for easychair.bib;
 wenzelm parents: 
58589diff
changeset | 585 | ignored_line | 
| 
472b9fbcc7f0
back to liberal spaces of official syntax (in contrast to 4b190c763097), e.g. relevant for easychair.bib;
 wenzelm parents: 
58589diff
changeset | 586 | |
| 
472b9fbcc7f0
back to liberal spaces of official syntax (in contrast to 4b190c763097), e.g. relevant for easychair.bib;
 wenzelm parents: 
58589diff
changeset | 587 | case item_ctxt: Item => | 
| 58591 | 588 | body_line(item_ctxt) | | 
| 58590 
472b9fbcc7f0
back to liberal spaces of official syntax (in contrast to 4b190c763097), e.g. relevant for easychair.bib;
 wenzelm parents: 
58589diff
changeset | 589 | ignored_line | 
| 
472b9fbcc7f0
back to liberal spaces of official syntax (in contrast to 4b190c763097), e.g. relevant for easychair.bib;
 wenzelm parents: 
58589diff
changeset | 590 | |
| 58530 | 591 |         case _ => failure("")
 | 
| 592 | } | |
| 593 | } | |
| 58528 | 594 | } | 
| 58523 | 595 | |
| 596 | ||
| 58528 | 597 | /* parse */ | 
| 58523 | 598 | |
| 599 | def parse(input: CharSequence): List[Chunk] = | |
| 64824 | 600 |     Parsers.parseAll(Parsers.rep(Parsers.chunk), Scan.char_reader(input)) match {
 | 
| 58523 | 601 | case Parsers.Success(result, _) => result | 
| 58526 | 602 |       case _ => error("Unexpected failure to parse input:\n" + input.toString)
 | 
| 58523 | 603 | } | 
| 58528 | 604 | |
| 75393 | 605 |   def parse_line(input: CharSequence, context: Line_Context): (List[Chunk], Line_Context) = {
 | 
| 64824 | 606 | var in: Reader[Char] = Scan.char_reader(input) | 
| 58528 | 607 | val chunks = new mutable.ListBuffer[Chunk] | 
| 608 | var ctxt = context | |
| 609 |     while (!in.atEnd) {
 | |
| 75420 | 610 | val result = Parsers.parse(Parsers.chunk_line(ctxt), in) | 
| 611 |       (result : @unchecked) match {
 | |
| 60215 | 612 | case Parsers.Success((x, c), rest) => chunks += x; ctxt = c; in = rest | 
| 58528 | 613 | case Parsers.NoSuccess(_, rest) => | 
| 614 |           error("Unepected failure to parse input:\n" + rest.source.toString)
 | |
| 615 | } | |
| 616 | } | |
| 617 | (chunks.toList, ctxt) | |
| 618 | } | |
| 67243 | 619 | |
| 620 | ||
| 621 | ||
| 622 | /** HTML output **/ | |
| 623 | ||
| 624 | private val output_styles = | |
| 625 | List( | |
| 67257 | 626 | "" -> "html-n", | 
| 67243 | 627 | "plain" -> "html-n", | 
| 628 | "alpha" -> "html-a", | |
| 629 | "named" -> "html-n", | |
| 630 | "paragraph" -> "html-n", | |
| 631 | "unsort" -> "html-u", | |
| 632 | "unsortlist" -> "html-u") | |
| 633 | ||
| 634 | def html_output(bib: List[Path], | |
| 67256 | 635 | title: String = "Bibliography", | 
| 67248 
68177abb2988
isabelle.preview presents bibtex database files as well;
 wenzelm parents: 
67243diff
changeset | 636 | body: Boolean = false, | 
| 67243 | 637 |     citations: List[String] = List("*"),
 | 
| 67257 | 638 | style: String = "", | 
| 75393 | 639 | chronological: Boolean = false | 
| 640 |   ): String = {
 | |
| 75394 | 641 |     Isabelle_System.with_tmp_dir("bibtex") { tmp_dir =>
 | 
| 67243 | 642 | /* database files */ | 
| 643 | ||
| 69367 | 644 | val bib_files = bib.map(_.drop_ext) | 
| 75393 | 645 |       val bib_names = {
 | 
| 69366 | 646 | val names0 = bib_files.map(_.file_name) | 
| 67243 | 647 | if (Library.duplicates(names0).isEmpty) names0 | 
| 648 |         else names0.zipWithIndex.map({ case (name, i) => (i + 1).toString + "-" + name })
 | |
| 649 | } | |
| 650 | ||
| 651 |       for ((a, b) <- bib_files zip bib_names) {
 | |
| 77035 | 652 | Isabelle_System.copy_file(a.bib, tmp_dir + Path.basic(b).bib) | 
| 67243 | 653 | } | 
| 654 | ||
| 655 | ||
| 656 | /* style file */ | |
| 657 | ||
| 658 | val bst = | |
| 659 |         output_styles.toMap.get(style) match {
 | |
| 660 | case Some(base) => base + (if (chronological) "c" else "") + ".bst" | |
| 661 | case None => | |
| 662 |             error("Bad style for bibtex HTML output: " + quote(style) +
 | |
| 663 | "\n(expected: " + commas_quote(output_styles.map(_._1)) + ")") | |
| 664 | } | |
| 73317 | 665 |       Isabelle_System.copy_file(Path.explode("$BIB2XHTML_HOME/bst") + Path.explode(bst), tmp_dir)
 | 
| 67243 | 666 | |
| 667 | ||
| 668 | /* result */ | |
| 669 | ||
| 670 |       val in_file = Path.explode("bib.aux")
 | |
| 671 |       val out_file = Path.explode("bib.html")
 | |
| 672 | ||
| 673 | File.write(tmp_dir + in_file, | |
| 674 |         bib_names.mkString("\\bibdata{", ",", "}\n") +
 | |
| 675 |         citations.map(cite => "\\citation{" + cite + "}\n").mkString)
 | |
| 676 | ||
| 677 | Isabelle_System.bash( | |
| 678 | "\"$BIB2XHTML_HOME/main/bib2xhtml.pl\" -B \"$ISABELLE_BIBTEX\"" + | |
| 67257 | 679 | " -u -s " + Bash.string(proper_string(style) getOrElse "empty") + | 
| 680 | (if (chronological) " -c" else "") + | |
| 77369 | 681 | if_proper(title, " -h " + Bash.string(title) + " ") + | 
| 67256 | 682 | " " + File.bash_path(in_file) + " " + File.bash_path(out_file), | 
| 80224 
db92e0b6a11a
clarified signature: prefer symbolic isabelle.Path over physical java.io.File;
 wenzelm parents: 
79503diff
changeset | 683 | cwd = tmp_dir).check | 
| 67243 | 684 | |
| 685 | val html = File.read(tmp_dir + out_file) | |
| 686 | ||
| 67248 
68177abb2988
isabelle.preview presents bibtex database files as well;
 wenzelm parents: 
67243diff
changeset | 687 |       if (body) {
 | 
| 
68177abb2988
isabelle.preview presents bibtex database files as well;
 wenzelm parents: 
67243diff
changeset | 688 | cat_lines( | 
| 
68177abb2988
isabelle.preview presents bibtex database files as well;
 wenzelm parents: 
67243diff
changeset | 689 | split_lines(html). | 
| 
68177abb2988
isabelle.preview presents bibtex database files as well;
 wenzelm parents: 
67243diff
changeset | 690 |             dropWhile(line => !line.startsWith("<!-- BEGIN BIBLIOGRAPHY")).reverse.
 | 
| 
68177abb2988
isabelle.preview presents bibtex database files as well;
 wenzelm parents: 
67243diff
changeset | 691 |             dropWhile(line => !line.startsWith("<!-- END BIBLIOGRAPHY")).reverse)
 | 
| 
68177abb2988
isabelle.preview presents bibtex database files as well;
 wenzelm parents: 
67243diff
changeset | 692 | } | 
| 
68177abb2988
isabelle.preview presents bibtex database files as well;
 wenzelm parents: 
67243diff
changeset | 693 | else html | 
| 75394 | 694 | } | 
| 67243 | 695 | } | 
| 76972 | 696 | |
| 697 | ||
| 698 | ||
| 699 | /** cite commands and antiquotations **/ | |
| 700 | ||
| 77014 | 701 | /* cite commands */ | 
| 702 | ||
| 703 | def cite_commands(options: Options): List[String] = | |
| 77218 | 704 |     space_explode(',', options.string("document_cite_commands"))
 | 
| 77014 | 705 | |
| 706 | val CITE = "cite" | |
| 707 | val NOCITE = "nocite" | |
| 708 | ||
| 709 | ||
| 77020 | 710 | /* citations within theory source */ | 
| 77012 | 711 | |
| 77015 | 712 |   object Cite {
 | 
| 77016 | 713 | def unapply(tree: XML.Tree): Option[Inner] = | 
| 714 |       tree match {
 | |
| 715 | case XML.Elem(Markup(Markup.Latex_Cite.name, props), body) => | |
| 716 | val kind = Markup.Kind.unapply(props).getOrElse(CITE) | |
| 717 | val citations = Markup.Citations.get(props) | |
| 718 | val pos = props.filter(Markup.position_property) | |
| 719 | Some(Inner(kind, citations, body, pos)) | |
| 720 | case _ => None | |
| 721 | } | |
| 722 | ||
| 77024 | 723 |     sealed case class Inner(kind: String, citations: String, location: XML.Body, pos: Position.T) {
 | 
| 77016 | 724 | def nocite: Inner = copy(kind = NOCITE, location = Nil) | 
| 725 | ||
| 77025 
34219d664854
proper citations for unselected theories, notably for the default selection of the GUI panel;
 wenzelm parents: 
77024diff
changeset | 726 |       def latex_text: Latex.Text = {
 | 
| 
34219d664854
proper citations for unselected theories, notably for the default selection of the GUI panel;
 wenzelm parents: 
77024diff
changeset | 727 | val props = | 
| 
34219d664854
proper citations for unselected theories, notably for the default selection of the GUI panel;
 wenzelm parents: 
77024diff
changeset | 728 | (if (kind.nonEmpty) Markup.Kind(kind) else Nil) ::: | 
| 
34219d664854
proper citations for unselected theories, notably for the default selection of the GUI panel;
 wenzelm parents: 
77024diff
changeset | 729 | Markup.Citations(citations) ::: pos | 
| 
34219d664854
proper citations for unselected theories, notably for the default selection of the GUI panel;
 wenzelm parents: 
77024diff
changeset | 730 | List(XML.Elem(Markup.Latex_Cite(props), location)) | 
| 
34219d664854
proper citations for unselected theories, notably for the default selection of the GUI panel;
 wenzelm parents: 
77024diff
changeset | 731 | } | 
| 
34219d664854
proper citations for unselected theories, notably for the default selection of the GUI panel;
 wenzelm parents: 
77024diff
changeset | 732 | |
| 77024 | 733 | override def toString: String = citations | 
| 77016 | 734 | } | 
| 735 | ||
| 736 |     sealed case class Outer(kind: String, body: String, start: Isar_Token.Pos) {
 | |
| 737 | def pos: Position.T = start.position() | |
| 738 | ||
| 739 |       def parse: Option[Inner] = {
 | |
| 740 | val tokens = Isar_Token.explode(Parsers.keywords, body) | |
| 741 |         Parsers.parse_all(Parsers.inner(pos), Isar_Token.reader(tokens, start)) match {
 | |
| 742 | case Parsers.Success(res, _) => Some(res) | |
| 743 | case _ => None | |
| 744 | } | |
| 745 | } | |
| 746 | ||
| 747 | def errors: List[String] = | |
| 748 | if (parse.isDefined) Nil | |
| 749 |         else List("Malformed citation" + Position.here(pos))
 | |
| 750 | ||
| 751 | override def toString: String = | |
| 752 |         parse match {
 | |
| 753 | case Some(inner) => inner.toString | |
| 754 | case None => "<malformed>" | |
| 755 | } | |
| 756 | } | |
| 757 | ||
| 77015 | 758 |     object Parsers extends Parse.Parsers {
 | 
| 77017 | 759 | val keywords: Keyword.Keywords = Thy_Header.bootstrap_keywords + "in" + "using" | 
| 77015 | 760 | |
| 761 |       val location: Parser[String] = embedded ~ $$$("in") ^^ { case x ~ _ => x } | success("")
 | |
| 762 |       val citations: Parser[String] = rep1sep(name, $$$("and")) ^^ (x => x.mkString(","))
 | |
| 763 |       val kind: Parser[String] = $$$("using") ~! name ^^ { case _ ~ x => x } | success(CITE)
 | |
| 764 | ||
| 77016 | 765 | def inner(pos: Position.T): Parser[Inner] = | 
| 766 | location ~ citations ~ kind ^^ | |
| 767 |           { case x ~ y ~ z => Inner(z, y, XML.string(x), pos) }
 | |
| 77015 | 768 | } | 
| 769 | ||
| 770 | def parse( | |
| 771 | cite_commands: List[String], | |
| 772 | text: String, | |
| 773 | start: Isar_Token.Pos = Isar_Token.Pos.start | |
| 77016 | 774 |     ): List[Outer] = {
 | 
| 77015 | 775 | val controls = cite_commands.map(s => Symbol.control_prefix + s + Symbol.control_suffix) | 
| 776 | val special = (controls ::: controls.map(Symbol.decode)).toSet | |
| 777 | ||
| 778 | val Parsers = Antiquote.Parsers | |
| 779 |       Parsers.parseAll(Parsers.rep(Parsers.antiquote_special(special)), text) match {
 | |
| 780 | case Parsers.Success(ants, _) => | |
| 781 | var pos = start | |
| 77016 | 782 | val result = new mutable.ListBuffer[Outer] | 
| 77015 | 783 |           for (ant <- ants) {
 | 
| 784 |             ant match {
 | |
| 785 | case Antiquote.Control(source) => | |
| 786 |                 for {
 | |
| 787 | head <- Symbol.iterator(source).nextOption | |
| 788 | kind <- Symbol.control_name(Symbol.encode(head)) | |
| 789 |                 } {
 | |
| 790 | val rest = source.substring(head.length) | |
| 791 | val (body, pos1) = | |
| 792 | if (rest.isEmpty) (rest, pos) | |
| 793 | else (Scan.Parsers.cartouche_content(rest), pos.advance(Symbol.open)) | |
| 77016 | 794 | result += Outer(kind, body, pos1) | 
| 77015 | 795 | } | 
| 796 | case _ => | |
| 797 | } | |
| 798 | pos = pos.advance(ant.source) | |
| 799 | } | |
| 800 | result.toList | |
| 801 |         case _ => error("Unexpected failure parsing special antiquotations:\n" + text)
 | |
| 802 | } | |
| 803 | } | |
| 77011 
3e48f8c6afc9
parse citations from raw source, without formal context;
 wenzelm parents: 
77010diff
changeset | 804 | } | 
| 77020 | 805 | |
| 806 | ||
| 807 |   /* update old forms: @{cite ...} and \cite{...} */
 | |
| 808 | ||
| 809 | def cite_antiquotation(name: String, body: String): String = | |
| 810 | """\<^""" + name + """>\<open>""" + body + """\<close>""" | |
| 811 | ||
| 812 |   def cite_antiquotation(name: String, location: String, citations: List[String]): String = {
 | |
| 813 | val body = | |
| 77368 | 814 | if_proper(location, Symbol.cartouche(location) + " in ") + | 
| 77020 | 815 |       citations.map(quote).mkString(" and ")
 | 
| 816 | cite_antiquotation(name, body) | |
| 817 | } | |
| 818 | ||
| 819 |   private val Cite_Command = """\\(cite|nocite|citet|citep)((?:\[[^\]]*\])?)\{([^}]*)\}""".r
 | |
| 820 | private val Cite_Macro = """\[\s*cite_macro\s*=\s*"?(\w+)"?\]\s*""".r | |
| 821 | ||
| 822 | def update_cite_commands(str: String): String = | |
| 823 |     Cite_Command.replaceAllIn(str, { m =>
 | |
| 824 | val name = m.group(1) | |
| 825 | val loc = m.group(2) | |
| 826 | val location = | |
| 827 |         if (loc.startsWith("[") && loc.endsWith("]")) loc.substring(1, loc.length - 1)
 | |
| 828 | else loc | |
| 77218 | 829 |       val citations = space_explode(',', m.group(3)).map(_.trim)
 | 
| 77020 | 830 | Regex.quoteReplacement(cite_antiquotation(name, location, citations)) | 
| 831 | }) | |
| 832 | ||
| 833 |   def update_cite_antiquotation(cite_commands: List[String], str: String): String = {
 | |
| 834 | val opt_body = | |
| 835 |       for {
 | |
| 836 |         str1 <- Library.try_unprefix("@{cite", str)
 | |
| 837 |         str2 <- Library.try_unsuffix("}", str1)
 | |
| 838 | } yield str2.trim | |
| 839 | ||
| 840 |     opt_body match {
 | |
| 841 | case None => str | |
| 842 | case Some(body0) => | |
| 843 | val (name, body1) = | |
| 844 |           Cite_Macro.findFirstMatchIn(body0) match {
 | |
| 845 | case None => (CITE, body0) | |
| 846 | case Some(m) => (m.group(1), Cite_Macro.replaceAllIn(body0, "")) | |
| 847 | } | |
| 848 |         val body2 = body1.replace("""\<close>""", """\<close> in""")
 | |
| 849 | if (cite_commands.contains(name)) cite_antiquotation(name, body2) | |
| 850 | else cite_antiquotation(CITE, body2 + " using " + quote(name)) | |
| 851 | } | |
| 852 | } | |
| 58523 | 853 | } |