08 Apr

Intelligence of a “non-intelligent” editor

I use Emacs as my main editor. There are still times when I start Eclipse or a similar IDE because I have a complicated run configuration set up for my old projects and I haven’t yet had time to migrate it. Some of my coworkers often speak about the power of an IDE or say something similar to “Why don’t you use a more intelligent IDE?”

But during my Emacs journey (going on for about a year now) I figured out why you don’t need too much intelligence. Please, don’t argue with me about Emacs being the most intelligent – I know it is (in a way), but the “intelligence” differs a lot comparing to IDEs like PyCharm or Eclipse or VisualStudio. They use complex parsers and state machines to try to figure out what are you trying to type and offer you the exact methods or object fields you might need. They are also great for learning a new language. Offering such a functionality with Emacs is more outsourced. For Python I use Jedi, for Ruby Rope and for JavaScript tern (which is amazing!).  But most of the time auto-complete-mode offers the best auto completion. It look’s up for words in your buffers (open files) and that pretty much covers 90% of your needs.

And all those integrations come to Emacs naturally. Emacs is nothing more than a lisp interpreter serving as an editor. The language is a bit strange for beginners but when you get to know it there is almost no limit to what feature you can extend or create. I use emacs for IRC (erc), versioning (magit), note taking (org-mode), file system managing (dired+) etc. At the moment I am even evaluating if I can replace my mail client with it. So you can always count on the fact that there probably isn’t a programming language or development procedure you could not do with Emacs.
I have three interesting examples to support my hypothesis.

The first one is projectile, one of my favorite Emacs extensions. It enables you a simple project support without any project configuration files (you can have them but they are not needed). When you open a file, projectile checks if it is under version control (git, mercurial). If it is, the project root becomes the directory under version control. Simple but efficient. Now you can search trough your project files or switch projects or find a file in a project.

snapshot2

The second example would be ibuffer with ibuffer-vc extension.  ibuffer is a emacs major mode that lists all buffers (opened files). With the extension, the buffers are grouped by their version control system project. Again: simple, but efficient.

snapshot1

The third example two of my own hacks (own customization) for python editing mode. I use both Python 2.7 and Python 3.4 and depend on virtualenv. I use syntax checking using the flymakes extension but the extension uses the default system python version which can get pretty annoying. Also, on some projects I use tabs as the default indendation and on others spaces but Emacs Python configuration is global. How to fix this, you ask? I implemented two simple hacks (I’m not really fond of them but they serve my needs). Before you say anything against hacking let me remind you that you probably tweaked your operating system because you hated the defaults. That’s hacking.

Spaces or tabs using projectile:

(setq py-spaces-projects '("project1" "project2"))

(setq auto-mode-alist (append '(("/*.\.py$" . python-mode)) auto-mode-alist))
(require 'projectile)

(defun python-mode-config ()
  (hook-mark-todo)
  (if (member (projectile-project-name) py-spaces-projects)
      (spaces-py-settings)
	(tabs-py-settings)))

(add-hook 'python-mode-hook 'python-mode-config)

(defun tabs-py-settings ()
  (interactive)
  (message "python: tabs")
  (setq indent-tabs-mode t)
  (setq python-indent 4)
  (setq tab-width 4))
(defun spaces-py-settings ()
  (interactive)
  (message "python: spaces")
  (setq indent-tabs-mode nil)
  (setq python-indent 4))

Syntax checking using virtualenv and projectile

This code is simple. If we are in a project and an virtual environment for that project exists (the names must mach, which in my case usually do) the code check if there is pyflakes installed. If it is, the pyflakes of the virtual environment is used, else the global one is (Python 2.7).

(defun virtualenv-flymake ()
  (defvar virtualenv-exec (concat "~/.virtualenvs/" (projectile-project-name) "/bin/pyflakes"))
  (if (file-exists-p virtualenv-exec)
      (setq flymake-python-pyflakes-executable virtualenv-exec)
	(setq flymake-python-pyflakes-executable "pyflakes"))
  (flymake-python-pyflakes-load))
(add-hook 'python-mode-hook 'virtualenv-flymake)

I am pretty much certain that all that code could be prettier or there is even a extension that solves my problem but I haven’t found a better solution yet (did not even bother much, these just work for me).

13 Mar

Using Research Everything by Zemanta

Do you ever miss a research tool when writing a new post on your WordPress blog? I’m talking about a tool where you could search the web from your compose dashboard and insert related links directly to your post.

When I write posts or articles or any study related documents I search the web for interesting and relevant literature. I was really happy when I found out that Google enables you a Research tool on Google Drive documents. But the biggest problem is that I’m too much of a nerd to use the usual office suites like Microsoft Office or Libreoffice or Google Drive. My workflow is somewhat unusual. I write most of the content in Emacs where I use AUTEX package to create PDF documents with LaTeX. So those tools are somewhat useless for most of the stuff I do.

Search Everything for WordPress Reborn, Now With Writing HelperEvery blog needs good search functionality. Visitors want to find content they desire, and the blogg…Feb 28 2014www.zemanta.com

Blogging with WordPress and EmacsWhen it comes to tools, I am a hedgehog rather than a fox. I like to have a small number of tools, a…Sep 27 2013blog.gregdetre.co.uk

When I blog with Emacs and when I blog with other toolsEnglish: org-mode logo: http://orgmode.org/worg/org-faq.php#unicorn (Photo credit: Wikipedia) I woul…Sep 16 2013sachachua.com

But when it comes to writing blog posts, Emacs fails. Well, not really, I could use Org-mode’s export to blog tool but I don’t know how to do that yet =). It would also be possible to create a research tool for Emacs (check out Howdoi). Until then I am bound to the WordPress compose page where the Research Everything is a must-have. You can get it here. It’s really only an add-on for the best WordPress search plugin – Search Everything.

And yeah guys, this post was created using Zemanta’s Research Everything =)

06 Feb

Some interesting stuff about include and functions in PHP

Let mi tell you a fun scenario. You are a web developer and you release your product on a third-party environment. Not only one product, but two or even three with a really similar code base. Then you find out that someone (or rather a group of people) tried to use all your products at once. On the same platform. And because you didn’t worry about that before, you find out on a nice and quiet morning, that there is some incompatibility which triggers an error. And not just any error, a fatal error which affects the whole platform. Of course, I am talking about PHP and WordPress.

Each plugin gets injected into a WordPress blog with include_once statements. There are four methods to include some external PHP code (like a plugin) in your file:

  • require
  • include
  • require_once
  • include_once

The basic difference between require and include is that if the file is missing or couldn’t be included because of an error, the require triggers a fatal error and include a warning. The _once postfix just means that the external file can only be included once and if the code tries to do it again, nothing happens (meaning that the code doesn’t get included again).

These were just basics. Now we are going to move to the interesting stuff.

 The power

The variable scope in the included PHP file is inherited from the line where it was called. This is great, because we can do something like this:

external-example1.php:

<?php
print $variable;
php &gt; $variable = 'Hello world 1!';
php &gt; include_once 'external-example1.php';
Hello world 1!
php &gt; $variable = 'Hello world 2!';
php &gt; include 'external-example1.php';
Hello world 2!
php &gt; $variable = 'Hello world 3!';
php &gt; include_once 'external-example1.php';
php &gt;

And the chaos

But seriously, we are talking about PHP here. Let me introduce you to my  today’s Wat. We have some example files, which I will call from PHP’s interactive shell. Note, I always closed the shell and reopened it again.

external-example2.php

<?php
if (!function_exists('test_fn')) {
        function test_fn() {
                print "Hello, test_fn!";
        }
}
else {
        print "test_fn already exists!\n";
}
php &gt; include 'external-example2.php';
php &gt; include 'external-example2.php';
test_fn already exists!
php &gt;

This is still pretty much expected. In the first run the function gets defined and in the second id doesn’t get redefined again. So now we can be sure that the declared functions belong to global scope.

external-example3.php

<?php
if (function_exists('test_fn')) {
        print "Function exists, do not redeclare it!\n";
        return;
}
else {
        function test_fn() {
                print "Hello, test_fn!";
        }
        print "test_fn declared.\n";
}
print "This line should always get printed except if the if-statement is true.\n";
php &gt; include 'external-example3.php';
test_fn declared.
This line should always get printed except if the if-statement is true.
php &gt; include 'external-example3.php';
Function exists, do not redeclare it!
php &gt;

It is only natural that we can put declarations in brackets and declare them when needed. But why the else statement? When the return is triggered, the script will stop anyway. So let’s rewrite external-example3.php to something prettier.

external-example4.php

<?php

if (function_exists('test_fn')) {
        print "Function exists, do not redeclare it!\n";
        return;
}

function test_fn() {
        print "Hello, test_fn!";
}
print "test_fn declared.\n";

print "This line should always get printed except if the if-statement is true.\n";
php &gt; include 'external-example4.php';
Function exists, do not redeclare it!
php &gt; include 'external-example4.php';
PHP Fatal error:  Cannot redeclare test_fn() (previously declared in /home/sigi/tmp/php/external-example4.php:9) in /home/sigi/tmp/php/external-example4.php on line 10

Fatal error: Cannot redeclare test_fn() (previously declared in /home/sigi/tmp/php/external-example4.php:9) in /home/sigi/tmp/php/external-example4.php on line 10
php &gt;

I hope you agree that this is really disturbing. I didn’t know about this and when I was debugging the products I was sure that WordPress had some business with it. I went trough WordPress documentation and code, trying to figure out the cause. My first idea was that WordPress includes the files more than once but that wasn’t the case. The second (probably stupid) idea was that WordPress does some recompiling on its own but I also didn’t find any proof. The last thing I did (which should have been the first, noted!) helped me understand what was going on. Or rather understand what wasn’t going on. I did some examples of my one. The first explanation I got is that PHP does some kind of sanity check before the file is included. I am extremely fond of PHP documentation but this isn’t mentioned anywhere in includerequireinclude_once and require_once pages. Then I did some googling and found this: User-defined functions.

My colleague mentioned that this looks like hoisting but this is not the case here. Well, not entirely. The “hoisting” happens on the script’s global scope but not internally for functions. The next example proves that.

<?php

print no_hoisting('wat') . "\n";

function no_hoisting($x) {
        return $x . $x . $x;
}

function test() {
        print test2() . "\n";
        function test2() {
                return 'This doesn\'t work';
        }
}

test();
php &gt; include 'external-example5.php';
watwatwat
PHP Fatal error:  Call to undefined function test2() in /home/sigi/tmp/php/external-example5.php on line 10

Fatal error: Call to undefined function test2() in /home/sigi/tmp/php/external-example5.php on line 10
php &gt;

And then I realized that I already knew that. I knew that the function declaration order isn’t important. I really disliked it because it can lead to many misunderstandings (like the one above), so I never put much thought into it.

So, the logical consequence of unimportant function order is that the functions get declared at the beginning of the script. This explains the above behavior and errors.

Point being, never intentionally ignore things you don’t like about a programming language. Never. Because they tend to stab you in the back if you give them an opportunity. And I gave them. Point taken. And kids, don’t do drugs, do PHP. It’s certainly not that dangerous but it can f**k your life just as well.