3.12. 4 ビジュアル→テキスト切り替え

 wp-admin/js/editor.js を改造する場合の、ビジュアル→テキスト切り替え用 JavaScript コードです。

コード

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// content reform for text editor
//   visual to text
function hk_editor_tmce2html( content ) {
    var pre_tags1, pre_tags2, line_break, code_names, code_types, tag1, str1, re_str, pattern00, pattern4, re_str4;
    // 1st common reform
    content = hk_editor_reform_1st( content );
    // empty content
    if ( content.length == 0 ) {
        return '';
    }
    // escape PRE tag
    pre_tags1 = new Array();
    pre_tags2 = new Array();
    line_break = true;
    content = hk_editor_escape_pre( content, pre_tags1, pre_tags2, line_break );
    // remove \n
    content = content.replace( /\n/g, '' );
    // short code check
    code_names = new Array();
    code_types = new Array();
    content = hk_short_code_check( content, code_names, code_types );
    // 2nd common reform
    content = hk_editor_reform_2nd( content, code_names, code_types );
    // insert linebreak before tag
    tag1 = 'p|div|/div|table|/tbody|tr|/tr|h1|h2|h3|h4|h5|h6|ul|/ul|ol|/ol|pre';
    str1 = '(?:' + tag1 + ')(?: |>)';
    re_str = new RegExp( '(<' + str1 + ')', 'ig' );
    content = content.replace( re_str, '\n$1' );
    // insert linebreak and 4 spaces before tag
    tag1 = 'li|td|th';
    str1 = '(?:' + tag1 + ')(?: |>)';
    re_str = new RegExp( '(<' + str1 + ')', 'ig' );
    content = content.replace( re_str, '\n    $1' );
    // insert linebreak after end tag
    tag1 = 'p|div|table|h1|h2|h3|h4|h5|h6|ul|ol|pre';
    str1 = '(?:' + tag1 + ')';
    re_str = new RegExp( '(</' + str1 + '>)', 'ig' );
    content = content.replace( re_str, '$1\n' );
    // insert linebreak after DIV tag
    content = content.replace( /<div( [^>]*>|>)/ig, '<div$1\n' );
    // insert linebreak after BR tag
    content = content.replace( /(<br [^>]*>)/ig, '$1\n' );
    // insert linebreak before amd after short code
    if ( code_names.length != 0 ) {
        for ( i in code_names ) {
            code_name = code_names[i];
            code_type = code_types[code_name];
            pattern00 = hk_short_code_pattern( code_name, code_type );
            pattern4 = '(' + pattern00 + ')(?!\\])';
            re_str4 = new RegExp( pattern4, 'ig' );
            content = content.replace( re_str4, '\n$1\n' );
        }
    }
    // \n\n -> \n
    content = content.replace( /\n+/g, '\n' );
    // put back PRE tag
    content = hk_editor_put_back_pre( content, pre_tags1, pre_tags2 );
    // trim
    content = content.trim();
    return content;
}

説明

 23行目までの処理は、“テキスト→ビジュアル切り替え”と似ていますのでそちらをご覧ください。
 24~55行目:htmlコードに改行を挿入し見やすくしています。

 このプログラムをお使いになる場合は、お使いになる方の自己責任でお願いします。

関連

更新日:2015/11/22
掲載日:2015/11/22