• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:JavaScriptでpreタグで囲まれたソースコードをtextareaにコピーする
#navi(../)
RIGHT:Posted by &author(aterai); at 2012-07-25
RIGHT:Posted by &author(aterai); at &time(2012-07-25);
* JavaScriptでpreタグで囲まれたソースコードをtextareaにコピーする [#c270c144]

#contents

** 概要 [#f8b8ce13]
以下、preタグで囲まれたソースコードを簡単にコピーする方法をテスト
- オリジナルは[http://userscripts.org/scripts/show/11438 pre to textarea for Greasemonkey]
-- preタグをtextareaにして簡単にコピーできるようにする
`pre`タグで囲まれたソースコードを簡単にコピーする

- オリジナルは、[http://userscripts.org/scripts/show/11438 pre to textarea for Greasemonkey]
-- `pre`タグをtextareaにして簡単にコピーできるようにする
-- [http://d.hatena.ne.jp/aterai/20080725/1216954636 preタグで囲まれたソースコードを簡単にコピーする方法 - てんぷらメモ@はてな]から移動の予定
- [http://terai.xrea.jp/data/javascript/pre2textarea.user.js pre2textarea.user.js] (Operaの場合、ユーザーJavaScriptフォルダにファイルをコピー)
- pre要素をダブルクリックすると、内容がtextareaに変換される
- `pre`要素をダブルクリックすると、内容が`textarea`に変換される
- `Java`のソースコードの場合、ファイル名を取得してダウンロード用のリンクを作成する
-- [[JavaScriptでソースコードからJavaのファイル名を取得する>JavaScript/JavaFileName]]

** ソースコード [#v391264a]
#gist(5441120)

** Bookmarklet版 [#rfe513cb]
- 名前
-- pre2textarea
- アドレス(YUI Compressor で圧縮)
 javascript:(function(){function d(g){var h=document.createElement("div");h.innerHTML=g.innerHTML.replace(/<br[ \/]*>/ig,"\n").replace(/<.*?>/mg,"");return h.childNodes[0].nodeValue.replace(/\xA0/g," ")}function c(g){g.parentNode.replaceChild(g.originalPre,g)}var e=function(j){var g=document.createElement("textarea"),h=this.getBoundingClientRect(),i=function(k){switch(k.type){case"keydown":if(k.keyCode=="27"){c(this)}break;case"dblclick":c(this)}};g.addEventListener("keydown",i,false);g.addEventListener("dblclick",i,false);g.style.width=h.width+"px";g.style.height=(h.height>240?240:h.height)+"px";g.originalPre=this;g.value=d(this);this.tx=g;this.parentNode.replaceChild(this.tx,this);this.tx.focus();this.tx.select()},f=document.getElementsByTagName("pre"),b=0,a=f.length;for(;b<a;b++){f[b].addEventListener("dblclick",e,false)}}());
-- `pre2textarea`
- アドレス(`YUI Compressor` で圧縮)
 javascript:(function(){function c(m,l,n){var j=new Blob([m],{type:l+";charset=UTF-8"}),i=document.createElement("a"),k=function(o){switch(o.type){case"dragstart":o.dataTransfer.setData("DownloadURL",[l,n,this.href].join(":"));break;case"dragend":this.parentNode.removeChild(this)}};i.addEventListener("dragstart",k,false);i.addEventListener("dragend",k,false);i.innerHTML="Download: "+n;i.setAttribute("download",n);window.URL=window.URL||window.webkitURL;i.href=window.URL.createObjectURL(j);return i}function e(j){var i=j.match(/public(?:\s|final)+(?:class|interface|enum)\s+([^<{\s]+)/m);return(i?i[1]:"Unknown")+".java"}function f(i){var j=document.createElement("div");j.innerHTML=i.innerHTML.replace(/<br[ \/]*>/ig,"\n").replace(/<.*?>/mg,"");return j.childNodes[0].nodeValue.replace(/\xA0/g," ")}function d(j){var i=j.downloadLink;j.parentNode.replaceChild(j.originalPre,j);if(i!=null&&i.parentNode){i.parentNode.removeChild(i)}}var g=function(n){var i=document.createElement("textarea"),l=this.getBoundingClientRect(),k,j,m=function(p){switch(p.type){case"copy":case"cut":var o=p.clipboardData;o.items.add(this.innerText,"text/plain");d(this);p.preventDefault();break;case"keydown":if(p.keyCode=="27"){d(this)}break;case"dblclick":d(this)}};i.addEventListener("copy",m,false);i.addEventListener("cut",m,false);i.addEventListener("keydown",m,false);i.addEventListener("dblclick",m,false);i.style.width=l.width+"px";i.style.height=(l.height>240?240:l.height)+"px";i.originalPre=this;i.value=f(this);this.tx=i;this.parentNode.replaceChild(this.tx,this);this.tx.focus();this.tx.select();k=e(i.value),k=((j=prompt("FileName",k))!=null)?j:k;i.downloadLink=c(i.value,"text/plain",k);i.parentNode.insertBefore(i.downloadLink,i.nextSibling)},h=document.getElementsByTagName("pre"),b=0,a=h.length;for(;b<a;b++){h[b].addEventListener("dblclick",g,false)}}());

** メモ: ローカルにドロップして保存(ファイル名付き) [#ua1c0148]
- [http://blog.futuresoftware.jp/?p=101 FutureSoftware開発日誌 Ver2.0 » HTML5のドラッグ&ドロップによるファイル保存]
-- Chromeでのみ動作
-- `Chrome`でのみ動作
-- ファイルとしてダウンロード可能

#code{{
function makeDraggableDownloadLink(text, mimeType, fileName) {
  var blob = new Blob([text], {type: mimeType}),
         a = document.createElement('a');
  a.appendChild(document.createTextNode("download"));
  a.setAttribute('download', fileName);
  window.URL = window.URL || window.webkitURL;
  a.href = window.URL.createObjectURL(blob);
  a.addEventListener("dragstart", function(e) {
    e.dataTransfer.setData("DownloadURL", [mimeType,fileName,this.href].join(':'));
  }, false);
  return a;
}
}}

** メモ: 直接クリップボードにコピー [#baa5f2ba]
- [http://javascripter.hatenablog.com/entry/20091230/1262191418 クリップボードにコピー - 素人がプログラミングを勉強していたブログ]
- [http://fukayatsu.github.com/blog/2012/07/22/markdown-linker-for-chrome/ markdown形式でリンクをクリップボードにコピーするchrome-extension作った - fukayatsu.dev()]

 //ie, chrome-extension???
 document.execCommand("copy");

** メモ: Clipboard API [#q55b37f8]
- Clipboard API が使用できる ChromeやOpera 12.50 の場合、コピー、カットすると自動的に元のpreに戻すことが可能
- `Clipboard API`が使用できる`Chrome`や`Opera 12.50`の場合、コピー、カットすると自動的に元の`pre`に戻すことが可能

#code{{
var listener = function(e) {
  var tx = document.createElement("textarea"),
    rect = this.getBoundingClientRect(),
    name, ret,
  closeListener = function(e) {
    switch(e.type) {
    case 'copy':
    case 'cut':
      var dataTransfer = e.clipboardData;
      dataTransfer.items.add(this.innerText, 'text/plain');
      cleanup(this);
      e.preventDefault();
      break;
    case 'keydown':
      if(e.keyCode=="27") { // ESC
        cleanup(this);
      }
      break;
    case 'dblclick':
      cleanup(this);
    }
  };
  tx.addEventListener('copy',     closeListener, false);
  tx.addEventListener('cut',      closeListener, false);
  tx.addEventListener("keydown",  closeListener, false);
  tx.addEventListener("dblclick", closeListener, false);
//......
}}

** 参考リンク [#led8cfb3]
- [http://userscripts.org/scripts/show/11438 pre to textarea for Greasemonkey]
-- http://sybian99.googlepages.com/preToTextarea.user.js
-- %%[http://d.hatena.ne.jp/Sybian/20070815/p2 preをtextareaに - Sybianの日記]%%
-- %%via: [http://kawatarou.info/note/opera/opera_userjs.htm Shishimushi - User JavaScript]%%
- [http://userscripts.org/scripts/review/73497 Source for "pre select" - Userscripts.org]
- [http://www.w3.org/TR/clipboard-apis/ Clipboard API and events]
- [http://my.opera.com/desktopteam/blog/2012/07/06/marlin-1250-swim Opera Desktop Team - First bite of 12.50 ‘Marlin’: Clipboard API, redesigned key event handling, -webkit- CSS, and Notification Center]
- [http://domes.lingua.heliohost.org/webapi/intro-webplatform1.html#section-1-3 クリップボード API - Introduction to the Web Platform - DOM ECMAScripting]

** コメント [#vf0fac74]
#comment