Skip to content

Instantly share code, notes, and snippets.

@rodrigorgs
Last active October 18, 2016 17:25
Show Gist options
  • Save rodrigorgs/4f977ea53759906ba90a20ecea9adb95 to your computer and use it in GitHub Desktop.
Save rodrigorgs/4f977ea53759906ba90a20ecea9adb95 to your computer and use it in GitHub Desktop.
Modifies an ODT file, replacing occurrences of [[id-label]] with sequential numbers (one sequence per id).
#!/usr/bin/env ruby
# enumerate-refs2.rb
# Author: Rodrigo Rocha <rodrigo@dcc.ufba.br>
# Date: 2016-10-18
# To install the dependency, run on terminal:
# gem install rubyzip
require 'zip'
class Referencer; end
def help_and_quit
puts ' Modifies an ODT file, replacing occurrences of [[id-label]]'
puts 'with sequential numbers (one sequence per id).'
puts ' Example: "See Figures [[fig-home]] and [[fig-detail]] and'
puts 'Table [[tab-data]]" becomes "See Figures 1 and 2 and Table 1"'
puts
puts "Usage: #{$0} file.odt"
exit 1
end
class Referencer
KEY_LAST_INDEX = '__last_index'
def initialize
@hash = {}
end
def hash_for_id(id)
@hash[id] = {KEY_LAST_INDEX => 0} unless @hash[id]
@hash[id]
end
def last_index_for_id(id)
hash = hash_for_id(id)
hash[KEY_LAST_INDEX]
end
def increment_last_index_for_id(id)
hash = hash_for_id(id)
hash[KEY_LAST_INDEX] += 1
end
def self.id_for_key(key)
if key.include?('-')
key.split('-')[0]
else
''
end
end
def index_for(key)
id = Referencer.id_for_key(key)
hash = hash_for_id(id)
index = hash[key]
if index.nil?
increment_last_index_for_id(id)
index = last_index_for_id(id)
hash[key] = index
end
index
end
end
if __FILE__ == $0
input_path = ARGV[0]
help_and_quit if input_path.nil?
referencer = Referencer.new
Zip::File.open(input_path) do |zip_file|
entry = zip_file.glob('content.xml').first
contents = entry.get_input_stream.read
contents.gsub!(/\[\[(.*?)\]\]/) do |m|
key = $1.gsub(/<.*?>/, '').strip
referencer.index_for(key)
end
zip_file.get_output_stream('content.xml'){ |f| f.write(contents) }
zip_file.commit
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment