WordPress / better-code-editing

[✅ Merged into 4.9-alpha] Better Code Editing WordPress plugin
https://wordpress.org/plugins/better-code-editing/
37 stars 16 forks source link

Add autocomplete hinting #50

Closed westonruter closed 7 years ago

westonruter commented 7 years ago

Ideally there would be a dropdown with hinting suggestions that appears when typing, though it seems CodeMirror only supports showing ctrl+space by default to show the dropdown.

westonruter commented 7 years ago

This is working pretty well:

--- a/better-code-editing.php
+++ b/better-code-editing.php
@@ -227,6 +227,8 @@ class Better_Code_Editing_Plugin {
                'mode' => 'text/css',
                'gutters' => array( 'CodeMirror-lint-markers' ),
                'lint' => true,
+               'hint' => 'auto',
+               'extraKeys' => array( "Ctrl-Space" => "autocomplete" ),
            ) );
        } elseif ( in_array( $extension, array( 'php', 'phtml', 'php3', 'php4', 'php5', 'php7', 'phps' ), true ) ) {
            $settings['codemirror']['mode'] = 'application/x-httpd-php';
@@ -325,6 +327,9 @@ class Better_Code_Editing_Plugin {
                    if ( ! empty( $settings['codemirror']['lint'] ) ) {
                        wp_enqueue_script( 'codemirror-addon-lint-css' );
                    }
+                   if ( ! empty( $settings['codemirror']['hint'] ) ) {
+                       wp_enqueue_script( 'codemirror-addon-hint-css' );
+                   }
                    break;
            }

diff --git a/wp-admin/js/code-editor.js b/wp-admin/js/code-editor.js
index 7a229f2..621c20e 100644
--- a/wp-admin/js/code-editor.js
+++ b/wp-admin/js/code-editor.js
@@ -98,6 +98,13 @@ if ( 'undefined' === typeof window.wp.codeEditor ) {
        // Keep track of the instances that have been created.
        wp.codeEditor.instances.push( editor );

+       editor.on( 'keyup', function ( _editor, event ) {
+           var enterKey = 13;
+           if ( ! editor.state.completionActive && event.keyCode !== enterKey ) {
+               CodeMirror.commands.autocomplete( editor, null, { completeSingle: false } );
+           }
+       });
+
        // Make sure the editor gets updated if the content was updated on the server (sanitization) but not updated in the editor since it was focused.
        editor.on( 'blur', function() {
            $textarea.data( 'next-tab-blurs', false );
westonruter commented 7 years ago

image

westonruter commented 7 years ago

Sourced from: https://stackoverflow.com/a/33021864/93579

A problem with this is the autocomplete list is showing too aggressively. It should only be shown after typing letter, not Tab. Also, hitting Esc should maybe close the autocomplete suggestions.

westonruter commented 7 years ago