Skip to content

Instantly share code, notes, and snippets.

@ryasmi
Created October 14, 2015 18:21
Show Gist options
  • Save ryasmi/917e7812b0366b9fbf22 to your computer and use it in GitHub Desktop.
Save ryasmi/917e7812b0366b9fbf22 to your computer and use it in GitHub Desktop.
function updateRefs(){var e=DocumentApp.getActiveDocument().getBody(),t=e.getText(),n=(e.editAsText(),e.findText("References").getElement().getParent()),i=[];for(n=n.getNextSibling();null!=n&&"LIST_ITEM"==n.getType();n=n.getNextSibling())i.push({element:n,text:n.getText(),prev_order:i.length+1,used_index:t.indexOf("["+(i.length+1)+"]")});Object.keys(i).sort(function(e,t){return i[e].used_index==i[t].used_index?0:-1==i[e].used_index?1:-1==i[t].used_index?-1:i[e].used_index<i[t].used_index?-1:i[e].used_index>i[t].used_index?1:void 0}).map(function(e){return i[e]}).map(function(t,n){return-1==t.used_index?(i[n].element.removeFromParent(),void e.appendListItem(t.text)):(e.replaceText("\\["+t.prev_order+"\\]","[a"+t.prev_order+"]"),i[n].element.setText(t.text),t)}).forEach(function(t,n){e.replaceText("\\[a"+t.prev_order+"\\]","["+(n+1)+"]")})}function citeWebsite(){var e=prompt("Who are the authors?"),t=prompt("What is the URL?"),n=prompt("What is the access date (month-date)?").split("-");n=ieeeDate(2==n.length&&new Date((new Date).getYear(),Number(n[0])-1,n[1]));var i=UrlFetchApp.fetch(t),r=i.getContentText(),d=r.match(/\<title\>(.+)\</),o=d&&d.length>0&&d[1]||t,a=ieeeDate(i.getAllHeaders()["Last-Modified"]),s=e+'. "'+o+'." Internet: '+t+", "+a+" ["+n+"].";cite(s)}function ieeeDate(e){var t=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];return e=e?new Date(e):new Date,t[e.getMonth()]+". "+e.getDate()+", "+e.getYear()}function prompt(e){var t=DocumentApp.getUi().prompt(e);return t.getResponseText()}function addCitation(){cite(prompt("Enter the reference text."))}function cite(e){if(e){var t=DocumentApp.getActiveDocument(),n=t.getBody(),i=n.findText("References").getElement().getParent(),r=1;for(i=i.getNextSibling();null!=i&&"LIST_ITEM"==i.getType();i=i.getNextSibling(),r+=1);var d=(n.insertListItem(n.getChildIndex(i),e),t.getCursor()),o=d.getOffset(),a=d.getElement(),s=a.getText();a.setText(s.slice(0,o)+" ["+r+"]"+s.slice(o)),t.setCursor(t.newPosition(a,o+(""+r).length+3))}}function onOpen(){DocumentApp.getUi().createMenu("Citer").addItem("Refresh references","updateRefs").addItem("Cite website","citeWebsite").addItem("Add citation","addCitation").addToUi()}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment